useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html
You cant directly access anything under the WEB-INF
foldere. When browsers request your CSS file, they can not see inside the WEB-INF folder.
Try putting your files css/css
folder under WebContent
.
And add the following in dispatcher servlet to grant access ,
<mvc:resources mapping="/css/**" location="/css/" />
similarly for your js files . A Nice example here on this
var data = [_x000D_
{ "name": "bill", "age": 20 },_x000D_
{ "name": "jhon", "age": 19 },_x000D_
{ "name": "steve", "age": 16 },_x000D_
{ "name": "larry", "age": 22 },_x000D_
null, null, null_x000D_
];_x000D_
_x000D_
//eliminate all the null values from the data_x000D_
data = data.filter(function(x) { return x !== null }); _x000D_
_x000D_
console.log("data: " + JSON.stringify(data));
_x000D_
Not an expert on encoding, but after reading these...
... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.
If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding
parameter on the out-file
cmdlet e.g.
write-output "hello" | out-file "enctest.txt" -encoding utf8
Nothing else you can do on the PowerShell front then, but the following post may well help you:.
If you are doing things programatically and are using a UITableViewController
without a UINavigationController
your best bet is to do the following in viewDidLoad
:
Swift 3
self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
Earlier Swift
self.tableView.contentInset = UIEdgeInsetsMake(20.0f, 0.0f, 0.0f, 0.0f);
The UITableViewController
will still scroll behind the status bar but won't be under it when scrolled to the top.
Here's a variation on this theme. I want to uninstall Cisco Amp, wait, and get the exit code. But the uninstall program starts a second program called "un_a" and exits. With this code, I can wait for un_a to finish and get the exit code of it, which is 3010 for "needs reboot". This is actually inside a .bat file.
If you've ever wanted to uninstall folding@home, it works in a similar way.
rem uninstall cisco amp, probably needs a reboot after
rem runs Un_A.exe and exits
rem start /wait isn't useful
"c:\program files\Cisco\AMP\6.2.19\uninstall.exe" /S
powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode
In addition to Ladislav Mrnka's answer:
If you are publishing and overriding container on Settings tab, you can set MultipleActiveResultSet to True. You can find this option by clicking Advanced... and it's going to be under Advanced group.
This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
// Warning: This approach can lead to deadlocks, see Edit #2
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}
static void Main()
{
ExecuteCommand("echo testing");
}
* EDIT *
Given the extra information in your comment below, I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).
This does work if the batch file is not located in C:\Windows\System32
. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom batch files or executables in the Windows directory is bad practice anyway.
* EDIT 2 *
It turns out that if the streams are read synchronously, a deadlock can occur, either by reading synchronously before WaitForExit
or by reading both stderr
and stdout
synchronously one after the other.
This should not happen if using the asynchronous read methods instead, as in the following example:
static void ExecuteCommand(string command)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Console.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine("ExitCode: {0}", process.ExitCode);
process.Close();
}
I had a similar issue when attempting to start a process without showing the console window. I tested with several different combinations of property values until I found one that exhibited the behavior I wanted.
Here is a page detailing why the UseShellExecute
property must be set to false.
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.createnowindow.aspx
Under Remarks section on page:
If the UseShellExecute property is true or the UserName and Password properties are not null, the CreateNoWindow property value is ignored and a new window is created.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fullPath;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
}
catch (Exception e)
{
throw;
}
I have a Windows service, and I added the following line to the constructor for my service:
using System.Diagnostics;
try {
Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
Debugger.Break();
}
When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.
But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.
I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.
But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized
even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.
public partial class Form1 : MetroForm
{
SqlConnection cn;
SqlCommand cm;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (!CheckDatabaseExist())
{
GenerateDatabase();
}
}
private bool CheckDatabaseExist()
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
try
{
con.Open();
return true;
}
catch
{
return false;
}
}
private void GenerateDatabase()
{
try
{
cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
cm = new SqlCommand(sb.ToString() , cn);
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch
{
}
try
{
//Application.StartupPath is the location where the application is Installed
//Here File Path Can Be Provided Via OpenFileDialog
if (File.Exists(Application.StartupPath + "\\script.sql"))
{
string script = null;
script = File.ReadAllText(Application.StartupPath + "\\script.sql");
string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
cn.Open();
foreach (string str in ScriptSplitter)
{
using (cm = cn.CreateCommand())
{
cm.CommandText = str;
cm.ExecuteNonQuery();
}
}
}
}
}
catch
{
}
}
}
I prefer to do it by using a BAT file.
With BAT file you have more control and can do whatever you want.
string batFileName = path + @"\" + Guid.NewGuid() + ".bat";
using (StreamWriter batFile = new StreamWriter(batFileName))
{
batFile.WriteLine($"YOUR COMMAND");
batFile.WriteLine($"YOUR COMMAND");
batFile.WriteLine($"YOUR COMMAND");
}
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c " + batFileName);
processStartInfo.UseShellExecute = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
Process p = new Process();
p.StartInfo = processStartInfo;
p.Start();
p.WaitForExit();
File.Delete(batFileName);
For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:
If destination is a file: echo f | [batch file path]
If folder: echo d | [batch file path]
It will essentially just pipe the letter after "echo" to the input of the batch file.
You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.
Workaround I ended up using to avoid all the complexity:
var outputFile = Path.GetTempFileName();
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args) + " > " + outputFile + " 2>&1");
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(File.ReadAllText(outputFile)); //need the StandardOutput contents
So I create a temp file, redirect both the output and error to it by using > outputfile > 2>&1
and then just read the file after the process has finished.
The other solutions are fine for scenarios where you want to do other stuff with the output, but for simple stuff this avoids a lot of complexity.
Here is a trick with what you want to achieve. I was also having problem like you.
Its hard to get selected row and data key in RowDeleting Event But it is very easy to get selected row and datakeys in SelectedIndexChanged event. Here's an example-
protected void gv_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gv.SelectedIndex;
int vehicleId = Convert.ToInt32(gv.DataKeys[index].Value);
SqlConnection con = new SqlConnection("-----");
SqlCommand com = new SqlCommand("DELETE FROM tbl WHERE vId = @vId", con);
com.Parameters.AddWithValue("@vId", vehicleId);
con.Open();
com.ExecuteNonQuery();
}
Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.
grunt-contrib-uglify
gulp-uglify
--create_source_map
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
Since div's by default are block
elements - meaning they will occupy full available width, try using -
display:inline-block;
The div
is now rendered inline i.e. does not disrupt flow of elements, but will still be treated as a block element.
I find this technique easier than wrestling with float
s.
See this tutorial for more - http://learnlayout.com/inline-block.html. I would recommend even the previous articles that lead up to that one. (No, I did not write it)
First I recommand you can try use print and observe the action:
for i in range(0, 5, 1):
print i
the result:
0
1
2
3
4
You can understand the function principle.
In fact, range
scan range is from 0
to 5-1
.
It equals 0 <= i < 5
When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.
You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.
for i in range(5, 0, -1):
print i
the result:
5
4
3
2
1
Thus it can be seen, it equals 5 >= i > 0
You want to implement your java code in python:
for (int index = last-1; index >= posn; index--)
It should code this:
for i in range(last-1, posn-1, -1)
You forgot the return types in your member function definitions:
int ttTree::ttTreeInsert(int value) { ... }
^^^
and so on.
This is old thread but answer because if useful to anyone.
Step 1. Your Db Storage Engine set to InnoDB
Step 2. Create Primary Table
here customer
is primary table and customer_id
is primary key
Step 3. create foreign key table and give index
here we have customer_addresses
as related table and store customer addresses, so here customer_id
relation with customer
table
we can select index directly when create table as below
If you forgot to give index when create a table, then you can give index from the structure tab of table as below.
Step 4. Once index give to the field, Go to structure tab and click on Relation View as shown in below pic
Step 5. Now select the ON DELETE and ON UPDATE what you want to do, Select column from current table, select DB (SAME DB), select relation table and primary key from that table as shown in below pic and Save it
Now check if relation are give successfully, go to foreign table data list and click on foreign key value, you will redirect to primary table record, then relation made successfully.
The required SQL will be some like:-
SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....
Hope it helps.
//Inheritance
class A {
int i = 10;
public String getVal() {
return "I'm 'A'";
}
}
class B extends A {
int j = 20;
public String getVal() {
return "I'm 'B'";
}
}
class C extends B {
int k = 30;
public String getVal() {
return "I'm 'C'";
}
}
//Methods
public static boolean isInheritedClass(Object parent, Object child) {
if (parent == null || child == null) {
return false;
} else {
return isInheritedClass(parent.getClass(), child.getClass());
}
}
public static boolean isInheritedClass(Class<?> parent, Class<?> child) {
if (parent == null || child == null) {
return false;
} else {
if (parent.isAssignableFrom(child)) {
// is child or same class
return parent.isAssignableFrom(child.getSuperclass());
} else {
return false;
}
}
}
// Test the code
System.out.println("isInheritedClass(new A(), new B()):" + isInheritedClass(new A(), new B()));
System.out.println("isInheritedClass(new A(), new C()):" + isInheritedClass(new A(), new C()));
System.out.println("isInheritedClass(new A(), new A()):" + isInheritedClass(new A(), new A()));
System.out.println("isInheritedClass(new B(), new A()):" + isInheritedClass(new B(), new A()));
System.out.println("isInheritedClass(A.class, B.class):" + isInheritedClass(A.class, B.class));
System.out.println("isInheritedClass(A.class, C.class):" + isInheritedClass(A.class, C.class));
System.out.println("isInheritedClass(A.class, A.class):" + isInheritedClass(A.class, A.class));
System.out.println("isInheritedClass(B.class, A.class):" + isInheritedClass(B.class, A.class));
//Result
isInheritedClass(new A(), new B()):true
isInheritedClass(new A(), new C()):true
isInheritedClass(new A(), new A()):false
isInheritedClass(new B(), new A()):false
isInheritedClass(A.class, B.class):true
isInheritedClass(A.class, C.class):true
isInheritedClass(A.class, A.class):false
isInheritedClass(B.class, A.class):false
I previously had this problem with my EC2 instance (I was serving couchdb to serve resources -- am considering Amazon's S3 for the future).
One thing to check (assuming Ec2) is that the couchdb port is added to your open ports within your security policy.
I specifically encountered
"[Errno 111] Connection refused"
over EC2 when the instance was stopped and started. The problem seems to be a pidfile race. The solution for me was killing couchdb (entirely and properly) via:
pkill -f couchdb
and then restarting with:
/etc/init.d/couchdb restart
The error is that you cannot initialize a static const char*
within the class. You can only initialize integer variables there.
You need to declare the member variable in the class, and then initialize it outside the class:
// header file
class Foo {
static const char *SOMETHING;
// rest of class
};
// cpp file
const char *Foo::SOMETHING = "sommething";
If this seems annoying, think of it as being because the initialization can only appear in one translation unit. If it was in the class definition, that would usually be included by multiple files. Constant integers are a special case (which means the error message perhaps isn't as clear as it might be), and compilers can effectively replace uses of the variable with the integer value.
In contrast, a char*
variable points to an actual object in memory, which is required to really exist, and it's the definition (including initialization) which makes the object exist. The "one definition rule" means you therefore don't want to put it in a header, because then all translation units including that header would contain the definition. They could not be linked together, even though the string contains the same characters in both, because under current C++ rules you've defined two different objects with the same name, and that's not legal. The fact that they happen to have the same characters in them doesn't make it legal.
My solution below is in es6 because I made use of const
if you prefer es5 you can replace all const
with var
.
const str = " Hello World! ";_x000D_
// const str = " ";_x000D_
_x000D_
checkForWhiteSpaces(str);_x000D_
_x000D_
function checkForWhiteSpaces(args) {_x000D_
const trimmedString = args.trim().length;_x000D_
console.log(checkStringLength(trimmedString)) _x000D_
return checkStringLength(trimmedString) _x000D_
}_x000D_
_x000D_
// If the browser doesn't support the trim function_x000D_
// you can make use of the regular expression below_x000D_
_x000D_
checkForWhiteSpaces2(str);_x000D_
_x000D_
function checkForWhiteSpaces2(args) {_x000D_
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;_x000D_
console.log(checkStringLength(trimmedString)) _x000D_
return checkStringLength(trimmedString)_x000D_
}_x000D_
_x000D_
function checkStringLength(args) {_x000D_
return args > 0 ? "not empty" : "empty string";_x000D_
}
_x000D_
Think of them as synonyms, both have a producer that sends stuff over to a consumer... In the end fields of instances are written into a byte stream and the other end foes the reverse ands up with the same instances.
NB - java RMI also contains support for transporting classes that are missing from the recipient...
If you want to use some variable, you may use this way:
String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");
Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience
When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.
If you want to style your site per device, you can use the user agent
value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.
You can see some standard resolutions in this link.
BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.
Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.
TIPS
Example
I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.
State of mind
Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.
Maybe you received an error when working with this table before. You can rename the table and try to remove it again.
ALTER TABLE `area` RENAME TO `area2`;
DROP TABLE IF EXISTS `area2`;
4 possible ways, use one you need.
val ll = findViewById<LinearLayout>(R.id.your_layout_id)
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
<LinearLayout
android:background="@{@color/white}"
OR more useful statement-
<LinearLayout
android:background="@{model.colorResId}"
<LinearLayout
android:background="#FFFFFF"
<LinearLayout
android:background="@color/white"
LinearLayout ll = (LinearLayout) findViewById(R.id.your_layout_id);
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
after few hours play with it and nearly become dull. miracle came to me, it work.
<pre>
var listname = [];
$.ajax({
url : wedding, // change to your local url, this not work with absolute url
success: function (data) {
callback(data);
}
});
function callback(data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
// $('#displayImage1').append( "<img src='" + wedding + val +"'>" );
listname.push(val);
}
});
}
function myfunction() {
alert (listname);
}
</pre>
Here is a way to do it without adding an ID to the form elements.
<form method="post">
...
<select name="List">
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
<select name="List">
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
...
</form>
public ActionResult OrderProcessor()
{
string[] ids = Request.Form.GetValues("List");
}
Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:
public class OrderModel
{
public string[] List { get; set; }
}
public ActionResult OrderProcessor(OrderModel model)
{
string[] ids = model.List;
}
Hope this helps.
if you want to do a get request with params and headers.
var params = {_x000D_
paramName1: paramValue1,_x000D_
paramName2: paramValue2_x000D_
}_x000D_
_x000D_
var headers = {_x000D_
headerName1: headerValue1,_x000D_
headerName2: headerValue2_x000D_
}_x000D_
_x000D_
Axios.get(url, {params, headers} ).then(res =>{_x000D_
console.log(res.data.representation);_x000D_
});
_x000D_
I'm aware this is a very old post, but I have found a solution which has only become available more recently AND enables nearly all Objective-C 2.0 features on the Windows platform.
With the advent of gcc 4.6, support for Objective-C 2.0 language features (blocks, dot syntax, synthesised properties, etc) was added to the Objective-C compiler (see the release notes for full details). Their runtime has also been updated to work almost identically to Apple's own Objective-C 2.0 runtime. In short this means that (almost) any program that will legitimately compile with Clang on a Mac will also compile with gcc 4.6 without modification.
As a side-note, one feature that is not available is dictionary/array/etc literals as they are all hard-coded into Clang to use Apple's NSDictionary, NSArray, NSNumber, etc classes.
However, if you are happy to live without Apple's extensive frameworks, you can. As noted in other answers, GNUStep and the Cocotron provide modified versions of Apple's class libraries, or you can write your own (my preferred option).
MinGW is one way to get GCC 4.6 on the Windows platform, and can be downloaded from The MinGW website. Make sure when you install it you include the installation of C, C++, Objective-C and Objective-C++. While optional, I would also suggest installing the MSYS environment.
Once installed, Objective-C 2.0 source can be compiled with:
gcc MyFile.m -lobjc -std=c99 -fobjc-exceptions -fconstant-string-class=clsname (etc, additional flags, see documentation)
MinGW also includes support for compiling native GUI Windows applications with the -mwindows
flag. For example:
g++ -mwindows MyFile.cpp
I have not attempted it yet, but I imagine if you wrap your Objective-C classes in Objective-C++ at the highest possible layer, you should be able to successfully intertwine native Windows GUI C++ and Objective-C all in the one Windows Application.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo 'php_'.$abc;?>
^[0-9]{1,45}$
is correct.
Much of the time when you ask for a dynamic object, you get an ExpandoObject (not in the question's anonymous-but-statically-typed example above, but you mention JavaScript and my chosen JSON parser JsonFx, for one, generates ExpandoObjects).
If your dynamic is in fact an ExpandoObject, you can avoid reflection by casting it to IDictionary, as described at http://msdn.microsoft.com/en-gb/library/system.dynamic.expandoobject.aspx.
Once you've cast to IDictionary, you have access to useful methods like .Item and .ContainsKey
You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as attribute, and -- as in your example -- the normal way to create them is to just assign to them in the __init__ method.
An exception is if your class uses slots, which is a fixed list of attributes that the class allows instances to have. Slots are explained in http://www.python.org/2.2.3/descrintro.html, but there are various pitfalls with slots; they affect memory layout, so multiple inheritance may be problematic, and inheritance in general has to take slots into account, too.
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Declare the a
element as display: inline-block
and drop the width and height from the li
element.
Alternatively, apply a float: left
to the li
element and use display: block
on the a
element. This is a bit more cross browser compatible, as display: inline-block
is not supported in Firefox <= 2 for example.
The first method allows you to have a dynamically centered list if you give the ul
element a width of 100% (so that it spans from left to right edge) and then apply text-align: center
.
Use line-height
to control the text's Y-position inside the element.
If you think about it, a body XRay scan (at the medical center) too needs this kind of measurement for estimating size of tumors. So they place a 1 Dollar Coin on the body, to do a comparative measurement.
Even newspaper is printed with some marks on the corners.
You need a reference to measure. May be you can get your person to wear a cap which has a few bright green circles. Once you recognize the size of the circle you can comparatively measure the remaining.
Or you can create a transparent 1 inch circle which will superimpose on the face, move the camera toward/away the face, aim your superimposed circle on that bright green circle on the cap. Then on your photo will be as per scale.
OperationDataContext odDataContext = new OperationDataContext();
var studentInfo = from student in odDataContext.STUDENTs
join course in odDataContext.COURSEs
on student.course_id equals course.course_id
select new { student.student_name, student.student_city, course.course_name, course.course_desc };
Where student and course tables have primary key and foreign key relationship
myList.Count is a method on the list object, it just returns the value of a field so is very fast. As it is a small method it is very likely to be inlined by the compiler (or runtime), they may then allow other optimization to be done by the compiler.
myList.Count() is calling an extension method (introduced by LINQ) that loops over all the items in an IEnumerable, so should be a lot slower.
However (In the Microsoft implementation) the Count extension method has a “special case” for Lists that allows it to use the list’s Count property, this means the Count() method is only a little slower than the Count property.
It is unlikely you will be able to tell the difference in speed in most applications.
So if you know you are dealing with a List use the Count property, otherwise if you have a "unknown" IEnumerabl, use the Count() method and let it optimise for you.
numpy.ndarray()
is a class, while numpy.array()
is a method / function to create ndarray
.
In numpy docs if you want to create an array from ndarray
class you can do it with 2 ways as quoted:
1- using array()
, zeros()
or empty()
methods:
Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)
) for instantiating an array.
2- from ndarray
class directly:
There are two modes of creating an array using __new__
:
If buffer is None, then only shape, dtype, and order are used.
If buffer is an object exposing the buffer interface, then all keywords are interpreted.
The example below gives a random array because we didn't assign buffer value:
np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None) array([[ -1.13698227e+002, 4.25087011e-303], [ 2.88528414e-306, 3.27025015e-309]]) #random
another example is to assign array object to the buffer example:
>>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3])
from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer
Conclusion: use numpy.array()
if you want to make a numpy.ndarray()
object"
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value
Here's a version to convert each value in a hex string to it's two's complement version.
In [5159]: twoscomplement('f0079debdd9abe0fdb8adca9dbc89a807b707f')
Out[5159]: '10097325337652013586346735487680959091'
def twoscomplement(hm):
twoscomplement=''
for x in range(0,len(hm)):
value = int(hm[x],16)
if value % 2 == 1:
twoscomplement+=hex(value ^ 14)[2:]
else:
twoscomplement+=hex(((value-1)^15)&0xf)[2:]
return twoscomplement
Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used System.gc()
. But here, in my case, it is absolutely crucial. Weird? YES!
finally
{
try
{
in.close();
in = null;
out.flush();
out.close();
out = null;
System.gc();
}
catch (IOException e)
{
logger.error(e.getMessage());
e.printStackTrace();
}
}
Using the following imports:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
Try this:
let fakeResponse = [1,2,3];
let delayedObservable = Observable.of(fakeResponse).delay(5000);
delayedObservable.subscribe(data => console.log(data));
UPDATE: RXJS 6
The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).
So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.
Use the following imports:
import { from, of } from 'rxjs';
import { delay } from 'rxjs/internal/operators';
import { concatMap } from 'rxjs/internal/operators';
Then use the following code:
const myArray = [1,2,3,4];
from(myArray).pipe(
concatMap( item => of(item).pipe ( delay( 1000 ) ))
).subscribe ( timedItem => {
console.log(timedItem)
});
It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.
My solution is:
sudo -E env "PATH=$PATH" n stable
Works fine for me.
Found it here: https://stackoverflow.com/a/29400598/861615
This happens because you have change default global packages directory
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
You have your arguments to the remote add
command reversed:
git remote add <NAME> <PATH>
So:
git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git
See git remote --help
for more information.
You can use the function subset
inside ggplot2
. Try this
library(ggplot2)
data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example
ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) +
geom_bar(stat="bin")
I really liked Al P's answer but wanted uniqueness enforced cheaply so I took it one step further - use a directory. There are some obvious limitations (directory file limits, invalid file names) but it should work for most cases.
hinit() {
rm -rf /tmp/hashmap.$1
mkdir -p /tmp/hashmap.$1
}
hput() {
printf "$3" > /tmp/hashmap.$1/$2
}
hget() {
cat /tmp/hashmap.$1/$2
}
hkeys() {
ls -1 /tmp/hashmap.$1
}
hdestroy() {
rm -rf /tmp/hashmap.$1
}
hinit ids
for (( i = 0; i < 10000; i++ )); do
hput ids "key$i" "value$i"
done
for (( i = 0; i < 10000; i++ )); do
printf '%s\n' $(hget ids "key$i") > /dev/null
done
hdestroy ids
It also performs a tad bit better in my tests.
$ time bash hash.sh
real 0m46.500s
user 0m16.767s
sys 0m51.473s
$ time bash dirhash.sh
real 0m35.875s
user 0m8.002s
sys 0m24.666s
Just thought I'd pitch in. Cheers!
Edit: Adding hdestroy()
Inside your AJAX callback you need to call the response
function; passing the array that contains items to display.
jQuery("input.suggest-user").autocomplete({
source: function (request, response) {
jQuery.get("usernames.action", {
query: request.term
}, function (data) {
// assuming data is a JavaScript array such as
// ["[email protected]", "[email protected]","[email protected]"]
// and not a string
response(data);
});
},
minLength: 3
});
If the response JSON does not match the formats accepted by jQuery UI autocomplete then you must transform the result inside the AJAX callback before passing it to the response callback. See this question and the accepted answer.
No one seems to love mac re-indentation, So here How I do it:
[
{ "keys": ["command+shift+i"], "command": "reindent"}
]
In Preferences > Key Binding - User
One more extra tip: add
{ "keys": ["command+0"], "command": "focus_side_bar" }
to have sidebar file tree view navigation using keyboard.
Note: Add , at the end of each {}, if you have more than one {} set of objects
public class SecondHighest {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* Find the second largest int item in an unsorted array.
* This solution assumes we have atleast two elements in the array
* SOLVED! - Order N.
* Other possible solution is to solve with Array.sort and get n-2 element.
* However, Big(O) time NlgN
*/
int[] nums = new int[]{1,2,4,3,5,8,55,76,90,34,91};
int highest,cur, secondHighest = -1;
int arrayLength = nums.length;
highest = nums[1] > nums[0] ? nums[1] : nums[0];
secondHighest = nums[1] < nums[0] ? nums[1] : nums[0];
if (arrayLength == 2) {
System.out.println(secondHighest);
} else {
for (int x = 0; x < nums.length; x++) {
cur = nums[x];
int tmp;
if (cur < highest && cur > secondHighest)
secondHighest = cur;
else if (cur > secondHighest && cur > highest) {
tmp = highest;
highest = cur;
secondHighest = tmp;
}
}
System.out.println(secondHighest);
}
}
}
Another solution but without using ng-click which still works even for other tags than <a>
:
<tr [routerLink]="['/about']">
This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494
(This is my first day with angular. Gentle feedback is welcome)
Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:
SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
FROM YOUR_TABLE t
Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...
Reference:
You should run the script as 'superuser', just add 'sudo' in front of the command and type your password when prompted.
So try:
sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
If this doesn't work, try adapting the permissions:
sudo chmod 755 /dvtcolorconvert.rb
sudo chmod 755 ~/Themes/ObsidianCode.xccolortheme
int main();
This is a simple declaration. It cannot take any command line arguments.
int main(int argc, char* argv[]);
This declaration is used when your program must take command-line arguments. When run like such:
myprogram arg1 arg2 arg3
argc
, or Argument Count, will be set to 4 (four arguments), and argv
, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram
) is included in the arguments!
Alternatively, you could use:
int main(int argc, char** argv);
This is also valid.
There is another parameter you can add:
int main (int argc, char *argv[], char *envp[])
The envp
parameter also contains environment variables. Each entry follows this format:
VARIABLENAME=VariableValue
like this:
SHELL=/bin/bash
The environment variables list is null-terminated.
IMPORTANT: DO NOT use any argv
or envp
values directly in calls to system()
! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system()
. There is almost always a better solution implemented through C libraries.
The simplest answer is a simple question - do you need your results to be repeatable? If yes then NOLOCKS is not appropriate under any circumstances
If you don't need repeatability then nolocks may be useful, especially if you don't have control over all processes connecting to the target database.
I faced the same problem as mentioned below.
PID file found but no matching process was found. Stop aborted.
Solution is to find the free space of the linux machine by using the following command
df -h
The above command shows my home directory was 100% used. Then identified which files to be removed by using the following command
du -h .
After removing, it was able to perform IO operation on the linux machine and the tomcat was able to start.
For Windows 10 if you want use pip in normal cmd, not only in Anaconda prompt. you need add 3 environment paths. like the followings:
D:\Anaconda3
D:\Anaconda3\Scripts
D:\Anaconda3\Library\bin
most people only add D:\Anaconda3\Scripts
A Bean is a POJO(Plain Old Java Object), which is managed by the spring container.
Spring containers create only one instance of the bean by default. ?This bean it is cached in memory so all requests for the bean will return a shared reference to the same bean.
The @Bean annotation returns an object that spring registers as a bean in application context.?The logic inside the method is responsible for creating the instance.
When do we use @Bean annotation?
When automatic configuration is not an option. For example when we want to wire components from a third party library, because the source code is not available so we cannot annotate the classes with @Component.
A Real time scenario could be that someone wants to connect to Amazon S3 bucket. Because the source is not available he would have to create a @bean.
@Bean
public AmazonS3 awsS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsKeyId, accessKey);
return AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}
Source for the code above -> https://www.devglan.com/spring-mvc/aws-s3-java
Because I mentioned @Component Annotation above.
@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.
Component annotation registers the class as a single bean.
CodeIgniter file upload optionally ...works perfectly..... :)
---------- controller ---------
function file()
{
$this->load->view('includes/template', $data);
}
function valid_file()
{
$this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');
if ($this->form_validation->run()==FALSE)
{
$this->file();
}
else
{
$config['upload_path'] = './documents/';
$config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile',FALSE))
{
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if($_FILES['userfile']['error'] != 4)
{
return false;
}
}
else
{
return true;
}
}
i just use this lines which makes it optionally,
if($_FILES['userfile']['error'] != 4)
{
return false;
}
$_FILES['userfile']['error'] != 4 is for file required to upload.
you can make it unnecessary by using $_FILES['userfile']['error'] != 4
, then it will pass this error for file required and works great with other types of errors if any by using return false ,
hope it works for u ....
There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).
XSS
XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:
" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="
This would be written into your form like so:
<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>
The best way to protect against this is to use htmlspecialchars()
to secure your input. This encodes characters such as <
into <
. For example:
<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>
You can read more about XSS here: https://www.owasp.org/index.php/XSS
Form Modification
If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.
I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg
with ../index.php
or ../db-connect.php
).
In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.
I think you want SYSDATE
, not GETDATE()
. Try it:
UPDATE TableName SET LastModifiedDate = (SELECT SYSDATE FROM DUAL);
I see great examples above but they all start with curly brackets (json map). Another option is to return a result based on computation. The result can also be a list of css class names (not just map). Example:
ng-class="(status=='active') ? 'enabled' : 'disabled'"
or
ng-class="(status=='active') ? ['enabled'] : ['disabled', 'alik']"
Explanation: If the status is active, the class enabled
will be used. Otherwise, the class disabled
will be used.
The list []
is used for using multiple classes (not just one).
Whenever I need to access config variables I tend to use: $this->config->config['variable_name'];
Yes, if you do a git rm <filename>
and commit & push those changes. The file will disappear from the repository for that changeset and future commits.
The file will still be available for the previous revisions.
Had this problem on windows 10, eclipse Neon Release (4.6.0) and MSYS2 installed. Eclipse kept complaining that "Program 'g++' not found in PATH” and "Program 'gcc' not found in PATH”, yet it was compiling and running my C++ code. From the command prompt, I could run g++.
Solution was to define the C++ Environmental variable for eclipse called 'PATH' to point to windows variable called 'path' also $(Path). Menus: Preferences>>C/C++>>Build>>Environment
Looks like eclipse is case sensitive with the name of this environmental, while windows doesn't care about the case.
I like how gitk
can show you exactly what was untracked or sitting in the index, but by default it will show those stash "commits" in the middle of all your other commits on the current branch.
The trick is to run gitk as follows:
gitk "stash@{0}^!"
(The quoting is there to make it work in Powershell but this way it should still work in other shells as well.)
If you look up this syntax in the gitrevisions help page you'll find the following:
The
r1^!
notation includes commit r1 but excludes all of its parents. By itself, this notation denotes the single commit r1.
This will apparently put gitk in such a mode that only the immediate parents of the selected commit are shown, which is exactly what I like.
If you want to take this further and list all stashes then you can run this:
gitk `git stash list '--pretty=format:%gd^!'`
(Those single quotes inside the backticks are necessary to appease Bash, otherwise it complains about the exclamation mark)
If you are on Windows and using cmd or Powershell:
gitk "--argscmd=git stash list --pretty=format:%gd^!"
In Android studio canary build(3.+), you can do the following:
File -> Project Structure -> Look in Modules Section, there are names of modules of your class. Click on the module in which you want to upgrade java to 1.8 version. -> Change "Source Compatibility" and "Target Compatibility" to 1.8 from 1.7 or lower. Do not change anything else. -> Click Apply
now gradle will re-sync and your error will be removed.
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
I guess a generic client-side JavaScript compression implementation would be a very expensive operation in terms of processing time as opposed to transfer time of a few more HTTP packets with uncompressed payload.
Have you done any testing that would give you an idea how much time there is to save? I mean, bandwidth savings can't be what you're after, or can it?
As others have answered, you need multiple ALTER TABLE
statements.
Try following:
ALTER TABLE tblcommodityOHLC alter column CC_CommodityContractID NUMERIC(18,0);
ALTER TABLE tblcommodityOHLC alter column CM_CommodityID NUMERIC(18,0);
InputProperty[] ip = new InputProperty[nvPairs.Length];
Or, you can use a list like so:
List<InputProperty> list = new List<InputProperty>();
InputProperty ip = new (..);
list.Add(ip);
update.items = list.ToArray();
Another thing I'd like to point out, in C# you can delcare your int variable use in a for loop right inside the loop:
for(int i = 0; i<nvPairs.Length;i++
{
.
.
}
And just because I'm in the mood, here's a cleaner way to do this method IMO:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = new List<InputProperty>();
foreach(var nvPair in nvPairs)
{
if (nvPair == null) break;
var inputProp = new InputProperty
{
Name = "udf:" + nvPair.Name,
Val = nvPair.Value
};
ip.Add(inputProp);
}
update.Items = ip.ToArray();
return update;
}
Here's a nice, tidy solution for you: (also see the live demo ->)
window.onload = function start() {
slide();
}
function slide() {
var currMarg = 0,
contStyle = document.getElementById('container').style;
setInterval(function() {
currMarg = currMarg == 1800 ? 0 : currMarg + 600;
contStyle.marginLeft = '-' + currMarg + 'px';
}, 3000);
}
Since you are trying to learn, allow me to explain how this works.
First we declare two variables: currMarg
and contStyle
. currMarg
is an integer that we will use to track/update what left margin the container should have. We declare it outside the actual update function (in a closure), so that it can be continuously updated/access without losing its value. contStyle
is simply a convenience variable that gives us access to the containers styles without having to locate the element on each interval.
Next, we will use setInterval
to establish a function which should be called every 3 seconds, until we tell it to stop (there's your infinite loop, without freezing the browser). It works exactly like setTimeout
, except it happens infinitely until cancelled, instead of just happening once.
We pass an anonymous function to setInterval
, which will do our work for us. The first line is:
currMarg = currMarg == 1800 ? 0 : currMarg + 600;
This is a ternary operator. It will assign currMarg
the value of 0
if currMarg
is equal to 1800
, otherwise it will increment currMarg
by 600
.
With the second line, we simply assign our chosen value to container
s marginLeft, and we're done!
Note: For the demo, I changed the negative values to positive, so the effect would be visible.
I solved the problem in this way:
and no more error.
This method name should do the trick:
Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);
More info on that in the section about query derivation of the reference docs.
You can also use matplotlib for this.
from matplotlib.image import imread
img = imread('abc.tiff')
print(type(img))
output:
<class 'numpy.ndarray'>
You can use pd.Series.isin
.
For "IN" use: something.isin(somewhere)
Or for "NOT IN": ~something.isin(somewhere)
As a worked example:
import pandas as pd
>>> df
country
0 US
1 UK
2 Germany
3 China
>>> countries_to_keep
['UK', 'China']
>>> df.country.isin(countries_to_keep)
0 False
1 True
2 False
3 True
Name: country, dtype: bool
>>> df[df.country.isin(countries_to_keep)]
country
1 UK
3 China
>>> df[~df.country.isin(countries_to_keep)]
country
0 US
2 Germany
Along the lines of @halfcube's suggestion, this works really well:
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
I was having this same problem and was able to resolve it by carefully redoing the Environment Variables:
Also, I made them all System Variables, not User Variables like the Maven instructions say. When you
echo %Path%
Make sure you can see the %M2% and %JAVA_HOME% variables completely expanded, i.e. :
C:\Users\afairchild>echo %Path%
C:\Program Files\Apache Software Foundation\apache-maven-3.0.4\bin;C:\Program Files\Java\jdk1.7.0_09\bin; [etc]
MyModel._meta.get_all_field_names()
was deprecated several versions back and removed in Django 1.10.
Here's the backwards-compatible suggestion from the docs:
from itertools import chain
list(set(chain.from_iterable(
(field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
for field in MyModel._meta.get_fields()
# For complete backwards compatibility, you may want to exclude
# GenericForeignKey from the results.
if not (field.many_to_one and field.related_model is None)
)))
Use any of the following groupby
and agg
recipes.
# Setup
df = pd.DataFrame({
'a': ['A', 'A', 'B', 'B', 'B', 'C'],
'b': [1, 2, 5, 5, 4, 6],
'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df
a b c
0 A 1 x
1 A 2 y
2 B 5 z
3 B 5 x
4 B 4 y
5 C 6 z
To aggregate multiple columns as lists, use any of the following:
df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)
b c
a
A [1, 2] [x, y]
B [5, 5, 4] [z, x, y]
C [6] [z]
To group-listify a single column only, convert the groupby to a SeriesGroupBy
object, then call SeriesGroupBy.agg
. Use,
df.groupby('a').agg({'b': list}) # 4.42 ms
df.groupby('a')['b'].agg(list) # 2.76 ms - faster
a
A [1, 2]
B [5, 5, 4]
C [6]
Name: b, dtype: object
Use the static Double.isNaN(double)
method, or your Double
's .isNaN()
method.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
You should not map score to player. You should map player (or his name) to score:
Map<Player, Integer> player2score = new HashMap<Player, Integer>();
Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);
In this case the task is trivial:
int score = player2score.get(player);
I think the underlying issue is permission for me
If you're dealing with large datasets (i.e. datasets with a high number of columns), the solution noted above can be manually cumbersome, and requires you to know which columns are numeric a priori.
Try this instead.
char_data <- read.csv(input_filename, stringsAsFactors = F)
num_data <- data.frame(data.matrix(char_data))
numeric_columns <- sapply(num_data,function(x){mean(as.numeric(is.na(x)))<0.5})
final_data <- data.frame(num_data[,numeric_columns], char_data[,!numeric_columns])
The code does the following:
This essentially automates the import of your .csv file by preserving the data types of the original columns (as character and numeric).
If they are two integers you can try a quick and dirty trick: Map<String, ?>
using the key as i+"#"+j
.
If the key i+"#"+j
is the same as j+"#"+i
try min(i,j)+"#"+max(i,j)
.
Egypt (free software)
KcacheGrind (GPL)
Graphviz (CPL)
CodeViz (GPL)
This might work for you:
sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
I had this problem and the problem was bootstrap.js wasn't load in Yii2 framework.First check is jquery loaded in inspect and then check bootstrap.js is loaded?If you used any tooltip Popper.js is needed before bootsrap.js.
You don't need an external library for parsing XML in Java. Java has come with built-in implementations for SAX and DOM for ages.
Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed in a similar question (namely that Aggregate and Concatenate fail with 0 elements).
string Result = String.Join(",", split.Select(s => s.Name));
or (if s
is not a string)
string Result = String.Join(",", split.Select(s => s.ToString()));
StringBuilder
) to implementAnd of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (for
, foreach
), which is why I was looking for a Linq solution in the first place.
In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use
handler.removeCallbacksAndMessages(null);
As per documentation,
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
For users of Contact Form 7 on Wordpress this method is working for me: I hide the v3 Recaptcha on all pages except those with Contact 7 Forms.
But this method should work on any site where you are using a unique class selector which can identify all pages with text input form elements.
First, I added a target style rule in CSS which can collapse the tile:
CSS
div.grecaptcha-badge.hide{
width:0 !important;
}
Then I added JQuery script in my header to trigger after the window loads so the 'grecaptcha-badge' class selector is available to JQuery, and can add the 'hide' class to apply the available CSS style.
$(window).load(function () {
if(!($('.wpcf7').length)){
$('.grecaptcha-badge').addClass( 'hide' );
}
});
My tile still will flash on every page for a half a second, but it's the best workaround I've found so far that I hope will comply. Suggestions for improvement appreciated.
GROUP_CONCAT has DISTINCT attribute:
SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ') FROM table
Look at an HTML parser such as TagSoup, HTMLCleaner or NekoHTML.
Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:
You're trying to cherry pick fd9f578, which was a merge with two parents.
Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.
Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.
The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.
If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.
If you determine you need to include the merge vs cherry-picking the related commits, you have two options:
(More complicated and obscure; also discards history) you can indicate which parent should apply.
Use the -m
option to do so. For example, git cherry-pick -m 1 fd9f578
will use the first parent listed in the merge as the base.
Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
(Simpler and more familiar; preserves history) you can use git merge
instead of git cherry-pick
.
git merge
, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.This might be an old thread, but I'd like to mention Appcelerator Titanium, which allows anyone versed in HTML5/JavaScript/CSS to develop iOS applications.
From StyleCop
private fields, public fields, constructors, properties, public methods, private methods
As StyleCop is part of the MS build process you could view that as a de facto standard
Basic method for beginners like me.
public void loadDataToJtable(ArrayList<String> liste){
rows = table.getRowCount();
cols = table.getColumnCount();
for (int i = 0; i < rows ; i++) {
for ( int k = 0; k < cols ; k++) {
for (int h = 0; h < list1.size(); h++) {
String b = list1.get(h);
b = table.getValueAt(i, k).toString();
}
}
}
}
Additionally, you can just sleep:
sleep(10)
Since the UITests run in another process, this works. I don’t know how advisable it is, but it works.
Actually there are quite a few methods.
int sum_of_elems = 0;
Classic for loop:
for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
sum_of_elems += *it;
Using a standard algorithm:
#include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0
to 0.0
or 0.0f
(thanks to nneonneo). See also the C++11 solution below.
b. Automatically keeping track of the vector type even in case of future changes:
#include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(),
decltype(vector)::value_type(0));
Using std::for_each
:
std::for_each(vector.begin(), vector.end(), [&] (int n) {
sum_of_elems += n;
});
Using a range-based for loop (thanks to Roger Pate):
for (auto& n : vector)
sum_of_elems += n;
You state in the comments that the returned JSON is this:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
You're telling Gson that you have an array of Post
objects:
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
You don't. The JSON represents exactly one Post
object, and Gson is telling you that.
Change your code to be:
Post post = gson.fromJson(reader, Post.class);
bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)
I had the same problem for my project Ratio.js and here's what I did.
Problem: Github.com prevents files from rendering/executing when the source is viewed by setting the content type/MIME to plain text.
Solution: Have a web page import the files.
Example:
Use jsfiddle.net or jsbin.com to create a webpage online then save it. Navigate to your file in Github.com and click the 'raw' button to get the direct link to the file. From there, import the file using the appropriate tag and attribute.
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
</head>
<body>
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
<script type="text/javascript" src="https://raw.github.com/LarryBattle/Ratio.js/master/src/Ratio.js"></script>
<script type="text/javascript" src="https://raw.github.com/LarryBattle/Ratio.js/master/tests/js/Ratio-testcases.js"></script>
</body>
</html>
Live Demo: http://jsfiddle.net/jKu4q/2/
Note: Note for jsfiddle.net you can get direct access to the result page by adding show
to the end of the url.
Like so: http://jsfiddle.net/jKu4q/2/show
Or....you could create a project page and render your HTML files from there. You can create a project page at http://pages.github.com/.
Once created you can then access the link through http://*accountName*.github.com/*projectName*/
Example: http://larrybattle.github.com/Ratio.js/
The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)
select *
from (
select PEAA.PresupuestoEtapaActividadId,
PEAH.PresupuestoEtapaActividadHistoricoId,
sum(PEAA.ValorTotalDesperdicioBase) as Base,
sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
from hgc.PresupuestoActividadAnalisis as PEAA
inner join hgc.PresupuestoEtapaActividad as PEA
on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId
group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId
) as t
where exists (
select 1
from (
select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId
from hgc.PresupuestoEtapaActividadHistorico as PEAH
group by PEAH.PresupuestoEtapaActividadId
) as ti
where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId
)
There are several libraries. Here are two examples:
Apache Commons Lang includes a special class to escape or unescape strings (CSV, EcmaScript, HTML, Java, Json, XML): org.apache.commons.lang3.StringEscapeUtils
.
Escape to CSV
String escaped = StringEscapeUtils
.escapeCsv("I said \"Hey, I am 5'10\".\""); // I said "Hey, I am 5'10"."
System.out.println(escaped); // "I said ""Hey, I am 5'10""."""
Unescape from CSV
String unescaped = StringEscapeUtils
.unescapeCsv("\"I said \"\"Hey, I am 5'10\"\".\"\"\""); // "I said ""Hey, I am 5'10""."""
System.out.println(unescaped); // I said "Hey, I am 5'10"."
* You can download it from here.
If you use OpenCSV, you will not need to worry about escape or unescape, only for write or read the content.
Writing file:
FileOutputStream fos = new FileOutputStream("awesomefile.csv");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
CSVWriter writer = new CSVWriter(osw);
...
String[] row = {
"123",
"John",
"Smith",
"39",
"I said \"Hey, I am 5'10\".\""
};
writer.writeNext(row);
...
writer.close();
osw.close();
os.close();
Reading file:
FileInputStream fis = new FileInputStream("awesomefile.csv");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
CSVReader reader = new CSVReader(isr);
for (String[] row; (row = reader.readNext()) != null;) {
System.out.println(Arrays.toString(row));
}
reader.close();
isr.close();
fis.close();
* You can download it from here.
There is no limit to the input of md5 that I know of. Some implementations require the entire input to be loaded into memory before passing it into the md5 function (i.e., the implementation acts on a block of memory, not on a stream), but this is not a limitation of the algorithm itself. The output is always 128 bits. Note that md5 is not an encryption algorithm, but a cryptographic hash. This means that you can use it to verify the integrity of a chunk of data, but you cannot reverse the hashing. Also note that md5 is considered broken, so you shouldn't use it for anything security-related (it's still fine to verify the integrity of downloaded files and such).
<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
Old question I know, but for the curious:
Believe it or not, this issue was solved ~2 decades ago with HTTP BASIC, which passes the value as base64 encoded username:password. (See http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)
You could do the same, so that the example above would become:
Authorization: FIRE-TOKEN MFBONUoxN0hCR1pIVDdKSjNYODI6ZnJKSVVOOERZcEtEdE9MQ3dvLy95bGxxRHpnPQ==
For even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.targetFunction();
...
}
...
Use LinearLayout.LayoutParams
instead of MarginLayoutParams
. Here's the documentation.
O.k. this is going to sound pretty absurd, but humor me.
For me the problem got resolved when I changed my statement to this :
SELECT * FROM `table`
I made two changes
1.) Made the table name lower case - I know !!
2.) Used the specific quote symbol = ` : It's the key above your TAB
The solution does sound absurd, but it worked and it's Saturday evening and I've been working since 9 a.m. - So I'll take it :)
Good luck.
I think the variable should be in the same block:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
if (isUserConnected)
{ // meaning that the viewing user has not been saved
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
</div>
}
}
Something like:
SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users
This allows you to make operations and show it as columns.
EDIT:
you can also use joins and show operations as columns:
SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country
FROM users u LEFT JOIN countries c ON u.country_id = c.id
Set the CommandText
as well, and call Fill
on the SqlAdapter
to retrieve the results in a DataSet
:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
bufio.Reader.ReadLine() works well. But if you want to read each line by a string, try to use ReadString('\n'). It doesn't need to reinvent the wheel.
I hope it works fine
For Activity :
ActivityCompat.requestPermissions(this,permissionsList,REQUEST_CODE);
For Fragment :
requestPermissions(permissionsList,REQUEST_CODE);
You should see Sublime Column Selection:
Using the Mouse
Different mouse buttons are used on each platform:
OS X
- Left Mouse Button + ?
OR: Middle Mouse Button
Add to selection: ?
- Subtract from selection: ?+?
Windows
- Right Mouse Button + Shift
OR: Middle Mouse Button
Add to selection: Ctrl
- Subtract from selection: Alt
Linux
Right Mouse Button + Shift
Add to selection: Ctrl
- Subtract from selection: Alt
Using the Keyboard
OS X
- Ctrl + Shift + ?
- Ctrl + Shift + ?
Windows
- Ctrl + Alt + ?
- Ctrl + Alt + ?
Linux
- Ctrl + Alt + ?
- Ctrl + Alt + ?
I think the error because the elements are undefined ,so you need to add window.onload
event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
I usually use numpy sum over the logical condition column:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2
This seems to me slightly shorter than the solution presented above
You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:
>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'
This would of course fail if there is multiple numbers in the input. a quick check would be:
assert(age in input_given)
and also:
assert(len(name)<len(input_given))
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
To print the N first characters you can remove the N+1 characters up to the end of line:
$ sed 's/.//5g' <<< "defn-test"
defn
SVG text background image
body {_x000D_
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='red' font-size='20'>I love SVG!</text></svg>");_x000D_
}
_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>
_x000D_
Here is an indented version of the CSS so you can understand better. Note that this does not work, you need to use the single liner SVG from the snippet above instead:
body {
background-image:url("data:image/svg+xml;utf8,
<svg xmlns='http://www.w3.org/2000/svg' version='1.1'
height='50px' width='120px'>
<text x='0' y='15' fill='red' font-size='20'>I love SVG!</text>
</svg>");
}
Not sure how portable this is (works on Firefox 31 and Chrome 36), and it is technically an image... but the source is inline and plain text, and it scales infinitely.
@senectus found that it works better on IE if you base64 encode it: https://stackoverflow.com/a/25593531/895245
You can use MODIFY COLUMN
to do this. Just do...
ALTER TABLE YourTable
MODIFY COLUMN your_column
your_previous_column_definition COMMENT "Your new comment"
substituting:
YourTable
with the name of your tableyour_column
with the name of your commentyour_previous_column_definition
with the column's column_definition, which I recommend getting via a SHOW CREATE TABLE YourTable
command and copying verbatim to avoid any traps.*Your new comment
with the column comment you want.For example...
mysql> CREATE TABLE `Example` (
-> `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
-> `some_col` varchar(255) DEFAULT NULL,
-> PRIMARY KEY (`id`)
-> );
Query OK, 0 rows affected (0.18 sec)
mysql> ALTER TABLE Example
-> MODIFY COLUMN `id`
-> int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Look, I''m a comment!';
Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE Example;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Example | CREATE TABLE `Example` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Look, I''m a comment!',
`some_col` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
* Whenever you use MODIFY
or CHANGE
clauses in an ALTER TABLE
statement, I suggest you copy the column definition from the output of a SHOW CREATE TABLE
statement. This protects you from accidentally losing an important part of your column definition by not realising that you need to include it in your MODIFY
or CHANGE
clause. For example, if you MODIFY
an AUTO_INCREMENT
column, you need to explicitly specify the AUTO_INCREMENT
modifier again in the MODIFY
clause, or the column will cease to be an AUTO_INCREMENT
column. Similarly, if the column is defined as NOT NULL
or has a DEFAULT
value, these details need to be included when doing a MODIFY
or CHANGE
on the column or they will be lost.
I find myself removing and re-adding the remote interpreter to fix this problem when Invalidating Caches or Refreshing Paths does not work.
I use vagrant and every once and awhile if I add a new VM to my multi-vm setup, the forwarded port changes and this seems to confuse PyCharm when it tries to use the wrong port for SSH. Changing the port doesn't seem to help the broken references.
There's also concat, but it doesn't get used much
select concat('a','b') from dual;
@WebWanderer 's answer is very close to the DateDiff using SQL server, but inaccurate. That is because of the usage of age() function.
e.g. days between '2019-07-29' and '2020-06-25' should return 332, however, using the age() function it will returns 327. Because the age() returns '10 mons 27 days" and it treats each month as 30 days which is incorrect.
You shold use the timestamp to get the accurate result. e.g.
ceil((select extract(epoch from (current_date::timestamp - <your_date>::timestamp)) / 86400))
select t1.*, sq.*
from table1 t1,
(select a,b,c from table2 ...) sq
where ...
There's another use I have for git mv
not mentioned above.
Since discovering git add -p
(git add's patch mode; see http://git-scm.com/docs/git-add), I like to use it to review changes as I add them to the index. Thus my workflow becomes (1) work on code, (2) review and add to index, (3) commit.
How does git mv
fit in? If moving a file directly then using git rm
and git add
, all changes get added to the index, and using git diff to view changes is less easy (before committing). Using git mv
, however, adds the new path to the index but not changes made to the file, thus allowing git diff
and git add -p
to work as usual.
You can use the below command, to check MongoDB status, e.g: sudo service MongoDB status
which displays the status of MongoDB service as like the screenshot:
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
Source: php.net in_array manual page.
SQL: show full processlist;
This is what the MySQL Workbench does.
The async way of life:
#! /usr/bin/node
const fs = require('fs');
function readall (stream)
{
return new Promise ((resolve, reject) => {
const chunks = [];
stream.on ('error', (error) => reject (error));
stream.on ('data', (chunk) => chunk && chunks.push (chunk));
stream.on ('end', () => resolve (Buffer.concat (chunks)));
});
}
function readfile (filename)
{
return readall (fs.createReadStream (filename));
}
(async () => {
let content = await readfile ('/etc/ssh/moduli').catch ((e) => {})
if (content)
console.log ("size:", content.length,
"head:", content.slice (0, 46).toString ());
})();
You are not passing your 2D array correctly. This should work for you
int rotateArr(int *arr[])
or
int rotateArr(int **arr)
or
int rotateArr(int arr[][N])
Rather than returning the array pass the target array as argument. See John Bode's answer.
You could solve this many ways. One that is pretty simple to understand is to just use a loop.
def comp(list1, list2):
for val in list1:
if val in list2:
return True
return False
A more compact way you can do it is to use map
and reduce
:
reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))
Even better, the reduce
can be replaced with any
:
any(map(lambda v: v in list2, list1))
You could also use sets:
len(set(list1).intersection(list2)) > 0
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
The file system of the container is in the data folder of docker, normally in /var/lib/docker. In order to start and inspect a running containers file system do the following:
hash=$(docker run busybox)
cd /var/lib/docker/aufs/mnt/$hash
And now the current working directory is the root of the container.
It doesn't matter if the random_state is 0 or 1 or any other integer. What matters is that it should be set the same value, if you want to validate your processing over multiple runs of the code. By the way I have seen random_state=42
used in many official examples of scikit as well as elsewhere also.
random_state
as the name suggests, is used for initializing the internal random number generator, which will decide the splitting of data into train and test indices in your case. In the documentation, it is stated that:
If random_state is None or np.random, then a randomly-initialized RandomState object is returned.
If random_state is an integer, then it is used to seed a new RandomState object.
If random_state is a RandomState object, then it is passed through.
This is to check and validate the data when running the code multiple times. Setting random_state
a fixed value will guarantee that same sequence of random numbers are generated each time you run the code. And unless there is some other randomness present in the process, the results produced will be same as always. This helps in verifying the output.
Steps:
All the commands and variables which begin with that letter are now going to appear
Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>
May be helpful for late comers.
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 2) {
cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
return -1;
}else{
Mat image;
Mat grayImage;
image = imread(argv[1], IMREAD_COLOR);
if (!image.data) {
cout << "Could not open the image file" << endl;
return -1;
}
else {
int height = image.rows;
int width = image.cols;
cvtColor(image, grayImage, CV_BGR2GRAY);
namedWindow("Display window", WINDOW_AUTOSIZE);
imshow("Display window", image);
namedWindow("Gray Image", WINDOW_AUTOSIZE);
imshow("Gray Image", grayImage);
cvWaitKey(0);
image.release();
grayImage.release();
return 0;
}
}
}
Here is a well tested function which i used for my projects with detailed self explanatory comments
There are many times when the ports other than 80 are blocked by server firewall so the code appears to be working fine on localhost but not on the server
function get_page($url){
global $proxy;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
curl_setopt($ch, CURLOPT_TIMEOUT, 200); // http request timeout 20 seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // the page encoding
$data = curl_exec($ch); // execute the http request
curl_close($ch); // close the connection
return $data;
}
============== This code goes in Module1 ============
Sub ShowProgress()
UserForm1.Show
End Sub
============== Module1 Code Block End =============
Create a Button on a Worksheet; map button to "ShowProgress" macro
Create a UserForm1 with 2 buttons, progress bar, bar box, text box:
UserForm1 = canvas to hold other 5 elements
CommandButton2 = Run Progress Bar Code; Caption:Run
CommandButton1 = Close UserForm1; Caption:Close
Bar1 (label) = Progress bar graphic; BackColor:Blue
BarBox (label) = Empty box to frame Progress Bar; BackColor:White
Counter (label) = Display the integers used to drive the progress bar
======== Attach the following code to UserForm1 =========
Option Explicit
' This is used to create a delay to prevent memory overflow
' remove after software testing is complete
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub UserForm_Initialize()
Bar1.Tag = Bar1.Width
Bar1.Width = 0
End Sub
Sub ProgressBarDemo()
Dim intIndex As Integer
Dim sngPercent As Single
Dim intMax As Integer
'==============================================
'====== Bar Length Calculation Start ==========
'-----------------------------------------------'
' This section is where you can use your own '
' variables to increase bar length. '
' Set intMax to your total number of passes '
' to match bar length to code progress. '
' This sample code automatically runs 1 to 100 '
'-----------------------------------------------'
intMax = 100
For intIndex = 1 To intMax
sngPercent = intIndex / intMax
Bar1.Width = Int(Bar1.Tag * sngPercent)
Counter.Caption = intIndex
'======= Bar Length Calculation End ===========
'==============================================
DoEvents
'------------------------
' Your production code would go here and cycle
' back to pass through the bar length calculation
' increasing the bar length on each pass.
'------------------------
'this is a delay to keep the loop from overrunning memory
'remove after testing is complete
Sleep 10
Next
End Sub
Private Sub CommandButton1_Click() 'CLOSE button
Unload Me
End Sub
Private Sub CommandButton2_Click() 'RUN button
ProgressBarDemo
End Sub
================= UserForm1 Code Block End =====================
============== This code goes in Module1 =============
Sub ShowProgress()
UserForm1.Show
End Sub
============== Module1 Code Block End =============
The answer works very well, just to add a angular directive in case you are using angular like me:
app.directive('popover', ['$document', function($document) {
return {
restrict: 'EA',
link: function(scope, elem, attrs) {
$(document).ready(function() {
$('[data-toggle="popover"]').popover();
});
elem.bind('click', function(e) {
$('#notification').popover('toggle');
})
$('body').on('click', function (e) {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!elem.is(e.target)
&& elem.has(e.target).length === 0
&& $('.popover').has(e.target).length === 0) {
elem.popover('hide');
}
});
}
};
}]);
The html code:
<a popover tabindex="0" role="button"
id="notification"
data-toggle="popover" data-trigger="manual"
data-container="body" data-placement="bottom"
data-content="This is a popover">
Popover button
</a>
It should have been as simple as use data-trigger='click focus'
, because according to bootstrap:
How popover is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space. manual cannot be combined with any other trigger.
However, use click and focus together doesn't work for me for unknown reason, instead I have to toggle it manually.
Use BoxDecoration
with BoxShadow
.
Here is a visual demo manipulating the following options:
The animated gif doesn't do so well with colors. You can try it yourself on a device.
Here is the full code for that demo:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ShadowDemo(),
),
);
}
}
class ShadowDemo extends StatefulWidget {
@override
_ShadowDemoState createState() => _ShadowDemoState();
}
class _ShadowDemoState extends State<ShadowDemo> {
var _image = NetworkImage('https://placebear.com/300/300');
var _opacity = 1.0;
var _xOffset = 0.0;
var _yOffset = 0.0;
var _blurRadius = 0.0;
var _spreadRadius = 0.0;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Center(
child:
Container(
decoration: BoxDecoration(
color: Color(0xFF0099EE),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, _opacity),
offset: Offset(_xOffset, _yOffset),
blurRadius: _blurRadius,
spreadRadius: _spreadRadius,
)
],
),
child: Image(image:_image, width: 100, height: 100,),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 80.0),
child: Column(
children: <Widget>[
Spacer(),
Slider(
value: _opacity,
min: 0.0,
max: 1.0,
onChanged: (newValue) =>
{
setState(() => _opacity = newValue)
},
),
Slider(
value: _xOffset,
min: -100,
max: 100,
onChanged: (newValue) =>
{
setState(() => _xOffset = newValue)
},
),
Slider(
value: _yOffset,
min: -100,
max: 100,
onChanged: (newValue) =>
{
setState(() => _yOffset = newValue)
},
),
Slider(
value: _blurRadius,
min: 0,
max: 100,
onChanged: (newValue) =>
{
setState(() => _blurRadius = newValue)
},
),
Slider(
value: _spreadRadius,
min: 0,
max: 100,
onChanged: (newValue) =>
{
setState(() => _spreadRadius = newValue)
},
),
],
),
),
)
],
);
}
}
With the excellent matplotlib
and numpy
packages
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
A roll your own function.
Supports recursion or not with the 2nd
switch.
Also, allow names of files with ;
which the accepted answer fails to address although a great answer, this will get over that issue.
The idea was taken from https://ss64.com/nt/empty.html
Notes within code.
@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written: 2020.01.26
:: Posted on the thread here: https://stackoverflow.com/q/10813943/8262102
:: Based on: https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>" = Your path wrapped in quotes.
:: <BOOLEAN> = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE = if directory doesn't exist.
:: 0-inf = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
) else if not "%~1"=="" (
set count=0 & set msg= & set dirExists=
if not exist "!%~1!" (set msg=FALSE)
if exist "!%~1!" (
if {%~2}=={TRUE} (
>nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
set msg=!count!
)
if {%~2}=={FALSE} (
for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
set msg=!count!
)
)
)
set "%~1=!msg!" & goto :eof
)
You may want something like this: http://addons.mozilla.org/en-US/firefox/addon/5648
I think there is a version for IE and also with Explorer Integration. Pretty good software.
<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />
<head>
<base href="${baseURL}" />
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
You should now use the .on()
function to bind events.
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
// use `new DepartmentFactory` as given below. `new` is imporatant
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
function sortOn(property){
return function(a, b){
if(a[property] < b[property]){
return -1;
}else if(a[property] > b[property]){
return 1;
}else{
return 0;
}
}
}
//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Here is how you do it:
In .h
#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif
extern "C" // Only if you are using C++ rather than C
{
EXPORT int __stdcall add2(int num);
EXPORT int __stdcall mult(int num1, int num2);
}
in .cpp
extern "C" // Only if you are using C++ rather than C
{
EXPORT int __stdcall add2(int num)
{
return num + 2;
}
EXPORT int __stdcall mult(int num1, int num2)
{
int product;
product = num1 * num2;
return product;
}
}
The macro tells your module (i.e your .cpp files) that they are providing the dll stuff to the outside world. People who incude your .h file want to import the same functions, so they sell EXPORT as telling the linker to import. You need to add BUILD_DLL to the project compile options, and you might want to rename it to something obviously specific to your project (in case a dll uses your dll).
You might also need to create a .def file to rename the functions and de-obfuscate the names (C/C++ mangles those names). This blog entry might be an interesting launching off point about that.
Loading your own custom dlls is just like loading system dlls. Just ensure that the DLL is on your system path. C:\windows\ or the working dir of your application are an easy place to put your dll.
Try the following code:
public static byte[] decode(String hex){
String[] list=hex.split("(?<=\\G.{2})");
ByteBuffer buffer= ByteBuffer.allocate(list.length);
System.out.println(list.length);
for(String str: list)
buffer.put(Byte.parseByte(str,16));
return buffer.array();
}
To convert to String just create a new String with the byte[] returned by the decode method.
It sounds like that if you request faq.html
the webserver signals your browser that the file is in UTF-8 encoding.
Check that with your browser which encoding is announced and used, please see the documentation of your browser how to do that. Every browser has this, most often accessible via the menu (to specify your preference which website's encoding should be used) and to see what the server returned, you often find this in page properties.
Then it sounds like that if you request faq.php
the webserver singals your browser that the file is in some other encoding. Probably no charset/encoding is given as per default PHP configuration setting. As it's a PHP file you can most often solve this by changing the PHP configuration default_charset
Docs directive:
default_charset = "UTF-8"
Locate your php.ini on the host and edit it accordingly.
If you don't have the php.ini available, you can change this by code as well by using the ini_set
Docs function:
ini_set('default_charset', 'UTF-8');
Take care that you change this very early in your script because PHP needs to be able to send out headers to have this working, and headers can't be set any longer if they have already been send.
Manually sending the Content-Type
header-line does work, too:
header('Content-Type: text/html; charset=UTF-8');
Additionally it's good practice that all the HTML pages you output have this header as well in their HTML <head>
section:
<html>
<head>
...
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
...
Hope this is helpful.
Replace measureScrapChild
to follow code:
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension)
{
View view = recycler.GetViewForPosition(position);
if (view != null)
{
MeasureChildWithMargins(view, widthSpec, heightSpec);
measuredDimension[0] = view.MeasuredWidth;
measuredDimension[1] = view.MeasuredHeight;
recycler.RecycleView(view);
}
}
I use xamarin, so this is c# code. I think this can be easily "translated" to Java.
Another way to see information is stat
command that will show more information. Command stat ~/.ssh
on my machine display
File: ‘/home/sumon/.ssh’ -> ‘/home/sumon/ssh-keys/.ssh.personal’
Size: 34 Blocks: 0 IO Block: 4096 symbolic link
Device: 801h/2049d Inode: 25297409 Links: 1
Access: (0777/lrwxrwxrwx) Uid: ( 1000/ sumon) Gid: ( 1000/ sumon)
Access: 2017-09-26 16:41:18.985423932 +0600
Modify: 2017-09-25 15:48:07.880104043 +0600
Change: 2017-09-25 15:48:07.880104043 +0600
Birth: -
Hope this may help someone.
Things like having %PATH% or spaces between items in your path will break it. Be warned.
Yes, windows paths that include spaces will cause errors. For example an application added this to the front of the system %PATH% variable definition:
C:\Program Files (x86)\WebEx\Productivity Tools;C:\Sybase\IQ-16_0\Bin64;
which caused all of the paths in %PATH% to not be set in the cmd window.
My solution is to demarcate the extended path variable in double quotes where needed:
"C:\Program Files (x86)\WebEx\Productivity Tools";C:\Sybase\IQ-16_0\Bin64;
The spaces are therefore ignored and the full path variable is parsed properly.
This would truncate the file:
$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);
In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER']
value.
Or, written in one line:
std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));
class CPhoenixDatabase():
def __init__(self, dbname):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def is_table(self, table_name):
""" This method seems to be working now"""
query = "SELECT name from sqlite_master WHERE type='table' AND name='{" + table_name + "}';"
cursor = self.conn.execute(query)
result = cursor.fetchone()
if result == None:
return False
else:
return True
Note: This is working now on my Mac with Python 3.7.1
Here is the best Maven-Environment Setup tutorial for Windows, Unix and Mac Operating systems.
But in the last you have to set value of PATH
variable as ";%M2_HOME%\bin"
instead of "%M2%"
, because PATH
variable is not able to reduce the value using "%M2%"
The following will check if the documents are equal using standard JDK libraries.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc1 = db.parse(new File("file1.xml")); doc1.normalizeDocument(); Document doc2 = db.parse(new File("file2.xml")); doc2.normalizeDocument(); Assert.assertTrue(doc1.isEqualNode(doc2));
normalize() is there to make sure there are no cycles (there technically wouldn't be any)
The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand xml:space
if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.
The problem with IIF(Fields!column.Value = "Approved", "Green") is that you are missing the third parameter. The correct syntax is IIF( [some boolean expression], [result if boolean expression is true], [result if boolean is false])
Try this
=IIF(Fields!Column.Value = "Approved", "Green", "No Color")
Here is a list of expression examples Expression Examples in Reporting Services
I solved it by
a) go to provisioning profile page on the portal
b) Click on Edit on the provisioning profile you are having trouble (right hand side).
c) Check the Appropriate Certificate box (not checked by default) and select the correct App ID (my old one was expired)
d) Download and use the new provisioning profile. Delete the old one(s).
Apparently there are 4 different causes of this problem:
- Your Keychain is missing the private key associated with your iPhone Developer or iPhone Distribution certificate.
- Your Keychain is missing the Apple Worldwide Developer Relations Intermediate Certificate.
- Your certificate was revoked or has expired.
- Online Certificate Status Protocol (OCSP) or Certificate Revocation List (CRL) are turned on in Keychain Access preferences
.
No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .
You can certainly extract that part of a string and that's a great way to parse out data. Regular expression syntax varies a lot so you need to reference the help file for the regex you're using. You might try a regular expression like:
[0-9]+ *[a-zA-Z]+,([0-9]+) *[a-zA-Z]+,[0-9]+ *[a-zA-Z]+
If your regex program can do string replacement then replace the entire string with the result you want and you can easily use that result.
You didn't mention if you're using bash or some other shell. That would help get better answers when asking for help.
The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:
Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.
There are many variants to versioning. It all boils down to personal preference.
For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.
The 'at' command.
"The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command."
You can try to do something like:
textView.getBackground().setAlpha(51);
Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
Use import javax.persistence.Entity; Instead of import org.hibernate.annotations.Entity;
Root certificates issued by CAs are just self-signed certificates (which may in turn be used to issue intermediate CA certificates). They have not much special about them, except that they've managed to be imported by default in many browsers or OS trust anchors.
While browsers and some tools are configured to look for the trusted CA certificates (some of which may be self-signed) in location by default, as far as I'm aware the openssl
command isn't.
As such, any server that presents the full chain of certificate, from its end-entity certificate (the server's certificate) to the root CA certificate (possibly with intermediate CA certificates) will have a self-signed certificate in the chain: the root CA.
openssl s_client -connect myweb.com:443 -showcerts
doesn't have any particular reason to trust Verisign's root CA certificate, and because it's self-signed you'll get "self signed certificate in certificate chain".
If your system has a location with a bundle of certificates trusted by default (I think /etc/pki/tls/certs
on RedHat/Fedora and /etc/ssl/certs
on Ubuntu/Debian), you can configure OpenSSL to use them as trust anchors, for example like this:
openssl s_client -connect myweb.com:443 -showcerts -CApath /etc/ssl/certs
LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.
I use the below approach.
reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)
reg.predict([[2136]])
Seems there is some demand to be able to access this statically.
How can I get such thing in static methods in non-spring-managed classes? – Aetherus
It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment()
before all beans have been created, since there is no guarantee when this component will be instantiated.
@Component
public class SpringContext
{
private static Environment environment;
public SpringContext(Environment environment) {
SpringContext.environment = environment;
}
public static Environment getEnvironment() {
if (environment == null) {
throw new RuntimeException("Environment has not been set yet");
}
return environment;
}
}
In my case the problem was that I hadn't Debug view open in Debug perspective, so:
1 - Be sure you have debug perspective opened:
2 - Be sure you have debug view opened:
The list from 2020-05-23 is:
31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22
The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:
whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
You can use this css code to get gutterless grid in bootstrap.
.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
margin-left: 0;
margin-right: 0;
}
.no-gutter>[class^="col-"]{
padding-left: 0;
padding-right: 0;
}
You can do this by calling the constructor each time with is slightly better
var tupleList = new List<Tuple<int, string>>
{
new Tuple<int, string>(1, "cow" ),
new Tuple<int, string>( 5, "chickens" ),
new Tuple<int, string>( 1, "airplane" )
};
For Rails 4.x the log level is configured a bit different than in Rails 3.x
Add this to config/environment/test.rb
# Enable stdout logger
config.logger = Logger.new(STDOUT)
# Set log level
config.log_level = :ERROR
The logger level is set on the logger instance from config.log_level
at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70
Environment variable
As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:
# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")
And then running tests from shell:
# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test
# Log level :ERROR
$ rake test
The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.
You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.
var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();
Solution
It is possible to use str_detect
of the stringr
package included in the tidyverse
package. str_detect
returns True
or False
as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr
package.
library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1 ? purrr 0.2.4
# ? tibble 1.4.2 ? dplyr 0.7.4
# ? tidyr 0.7.2 ? stringr 1.2.0
# ? readr 1.1.1 ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag() masks stats::lag()
mtcars$type <- rownames(mtcars)
mtcars %>%
filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl disp hp drat wt qsec vs am gear carb type
# 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
# 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
# 3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
# 4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
The good things about Stringr
We should use rather stringr::str_detect()
than base::grepl()
. This is because there are the following reasons.
stringr
package start with the prefix str_
, which makes the code easier to read.stringr
package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"
Benchmark
The results of the benchmark test are as follows. For large dataframe, str_detect
is faster.
library(rbenchmark)
library(tidyverse)
# The data. Data expo 09. ASA Statistics Computing and Graphics
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728 29
benchmark(
"str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
"grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
replications = 10,
columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2 grepl 10 16.480 1.513 16.195 0.248
# 1 str_detect 10 10.891 1.000 9.594 1.281
Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.
For me it works if I just do a
db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));
using SimpleJDBCTemplate or JDBCTemplate
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
I offer two recommendations:
1) Install the supervisor
package (more verbose instructions here):
sudo apt-get install supervisor
2) Create a config file for your daemon at /etc/supervisor/conf.d/flashpolicyd.conf
:
[program:flashpolicyd]
directory=/path/to/project/root
environment=ENV_VARIABLE=example,OTHER_ENV_VARIABLE=example2
command=python flashpolicyd.py
autostart=true
autorestart=true
3) Restart supervisor
to load your new .conf
supervisorctl update
supervisorctl restart flashpolicyd
[Unit]
Description=My Python daemon
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/project/main.py
WorkingDirectory=/opt/project/
Environment=API_KEY=123456789
Environment=API_PASS=password
Restart=always
RestartSec=2
[Install]
WantedBy=sysinit.target
Place this file into /etc/systemd/system/my_daemon.service
and enable it using systemctl daemon-reload && systemctl enable my_daemon && systemctl start my_daemon --no-block
.
To view logs:
systemctl status my_daemon
My solution for a cache implementation that stores optional NSAttributedString:
public static var attributedMessageTextCache = [String: NSAttributedString?]()
if attributedMessageTextCache.index(forKey: "key") != nil
{
if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
{
return attributedMessageText
}
return nil
}
TextChatCache.attributedMessageTextCache["key"] = .some(.none)
return nil
use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...
for more info about typescipt click here
Here one simple example I have created to share data between two controller using Typescript...
module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
sharedData: any;
constructor() {
this.sharedData = "send this data to Controller";
}
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);
//Create One controller for one purpose
export class FirstController {
dataInCtrl1: any;
//Don't forget to inject service to access data from service
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl1 = this.commonService.sharedData;
}
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
dataInCtrl2: any;
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl2 = this.commonService.sharedData;
}
}
angular.module('app').controller('SecondController', SecondController);
}
Here's some examples:
decimal a = 1.994444M;
Math.Round(a, 2); //returns 1.99
decimal b = 1.995555M;
Math.Round(b, 2); //returns 2.00
You might also want to look at bankers rounding / round-to-even with the following overload:
Math.Round(a, 2, MidpointRounding.ToEven);
There's more information on it here.
This is what Java internal code uses (on other compare
methods):
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
What if contentSize
is lower than bounds
?
For Swift it is:
scrollView.setContentOffset(CGPointMake(0, max(scrollView.contentSize.height - scrollView.bounds.size.height, 0) ), animated: true)
Have you tried Autodia yet? Last time I tried it it wasn't perfect, but it was good enough.
Here's a simple way to do it that I don't see in the other answers.
To round up to the second decimal place:
>>> n = 0.022499999999999999
>>>
>>> -(-n//.01) * .01
0.03
>>>
Other value:
>>> n = 0.1111111111111000
>>>
>>> -(-n//.01) * .01
0.12
>>>
With floats there's the occasional value with some minute imprecision, which can be corrected for if you're displaying the values for instance:
>>> n = 10.1111111111111000
>>>
>>> -(-n//0.01) * 0.01
10.120000000000001
>>>
>>> f"{-(-n//0.01) * 0.01:.2f}"
'10.12'
>>>
A simple roundup function with a parameter to specify precision:
>>> roundup = lambda n, p: -(-n//10**-p) * 10**-p
>>>
>>> # Or if you want to ensure truncation using the f-string method:
>>> roundup = lambda n, p: float(f"{-(-n//10**-p) * 10**-p:.{p}f}")
>>>
>>> roundup(0.111111111, 2)
0.12
>>> roundup(0.111111111, 3)
0.112
There is no standard support for renaming properties in JavaScriptSerializer
however you can quite easily add your own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;
public class JsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
List<MemberInfo> members = new List<MemberInfo>();
members.AddRange(type.GetFields());
members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));
object obj = Activator.CreateInstance(type);
foreach (MemberInfo member in members)
{
JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));
if (jsonProperty != null && dictionary.ContainsKey(jsonProperty.Name))
{
SetMemberValue(serializer, member, obj, dictionary[jsonProperty.Name]);
}
else if (dictionary.ContainsKey(member.Name))
{
SetMemberValue(serializer, member, obj, dictionary[member.Name]);
}
else
{
KeyValuePair<string, object> kvp = dictionary.FirstOrDefault(x => string.Equals(x.Key, member.Name, StringComparison.InvariantCultureIgnoreCase));
if (!kvp.Equals(default(KeyValuePair<string, object>)))
{
SetMemberValue(serializer, member, obj, kvp.Value);
}
}
}
return obj;
}
private void SetMemberValue(JavaScriptSerializer serializer, MemberInfo member, object obj, object value)
{
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
property.SetValue(obj, serializer.ConvertToType(value, property.PropertyType), null);
}
else if (member is FieldInfo)
{
FieldInfo field = (FieldInfo)member;
field.SetValue(obj, serializer.ConvertToType(value, field.FieldType));
}
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Type type = obj.GetType();
List<MemberInfo> members = new List<MemberInfo>();
members.AddRange(type.GetFields());
members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));
Dictionary<string, object> values = new Dictionary<string, object>();
foreach (MemberInfo member in members)
{
JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));
if (jsonProperty != null)
{
values[jsonProperty.Name] = GetMemberValue(member, obj);
}
else
{
values[member.Name] = GetMemberValue(member, obj);
}
}
return values;
}
private object GetMemberValue(MemberInfo member, object obj)
{
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
return property.GetValue(obj, null);
}
else if (member is FieldInfo)
{
FieldInfo field = (FieldInfo)member;
return field.GetValue(obj);
}
return null;
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return new[] { typeof(DataObject) };
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class JsonPropertyAttribute : Attribute
{
public JsonPropertyAttribute(string name)
{
Name = name;
}
public string Name
{
get;
set;
}
}
The DataObject
class then becomes:
public class DataObject
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("detail_level")]
public DetailLevel DetailLevel { get; set; }
}
I appreicate this might be a little late but thought other people wanting to use the JavaScriptSerializer
rather than the DataContractJsonSerializer
might appreciate it.
run the following
/usr/local/tomcat/bin/catalina.sh version
its response will be something like:
Using CATALINA_BASE: /usr/local/tomcat
Using CATALINA_HOME: /usr/local/tomcat
Using CATALINA_TMPDIR: /var/tmp/
Using JRE_HOME: /usr
Using CLASSPATH: /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_PID: /var/catalina.pid
Server version: Apache Tomcat/7.0.30
Server built: Sep 27 2012 05:13:37
Server number: 7.0.30.0
OS Name: Linux
OS Version: 2.6.32-504.3.3.el6.x86_64
Architecture: amd64
JVM Version: 1.7.0_60-b19
JVM Vendor: Oracle Corporation
I need my damn breakpoints! Very strange behavior - the normally red spot in Sources was going grey; these and debugger;
breakpoints would still appear to hit but show somewhere in some non-executable HTML.
After a couple hours of hacking away code the breakpoints were finally being hit correctly, however had more or less just the equivalent of "Hello World" left. Hahaha.
So I had some serverside data being output in the page (in my case in a @razor statement), but it would be the same in any similar case.
There was some incorrectly formed 0A/0D chars in the server output - the old carriage returns - causing Chrome the confusion with its own line numbering.
Cleaning the server injected HTML and I got my breakpoint.
Now let's see how much of this code I can CTRL-Z back...
I have created a tool that gets the job done. You can find it on my blog:
Besides colorizing your C# code, the tool also takes care of all the '<' and '>' symbols convering them to '<' and '&gt;'. Tabs are converted to spaces in order to look the same in different browsers. You can even make the colorizer inline the CSS styles, in case you cannot or you do not want to insert a CSS style sheet in you blog or website.
One liner is best
kill -9 $(lsof -i:PORT -t) 2> /dev/null
Example : On mac, wanted to clear port 9604. Following command worked like a charm
kill -9 $(lsof -i:9604 -t) 2> /dev/null
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
When adding new element with jquery plugin calls, you can do like the following:
$('<div>...</div>').hoverCard(function(){...}).appendTo(...)
Change table's default charset:
ALTER TABLE etape_prospection
CHARACTER SET utf8,
COLLATE utf8_general_ci;
To change string column charset exceute this query:
ALTER TABLE etape_prospection
CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;
This works for me for MS SQL server:
select * from test
where
year(date) = 2015
and month(date) = 10
and day(date)= 28 ;
1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.