Xcode 8.x • Swift 3.x or later
do {
// get the documents folder url
if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
// create the destination url for the text file to be saved
let fileURL = documentDirectory.appendingPathComponent("file.txt")
// define the string/text to be saved
let text = "Hello World !!!"
// writing to disk
// Note: if you set atomically to true it will overwrite the file if it exists without a warning
try text.write(to: fileURL, atomically: false, encoding: .utf8)
print("saving was successful")
// any posterior code goes here
// reading from disk
let savedText = try String(contentsOf: fileURL)
print("savedText:", savedText) // "Hello World !!!\n"
}
} catch {
print("error:", error)
}
Super late here and I still couldn't uninstall using sudo
as the other answers suggest. What did it for me was checking where cordova
was installed by running
which cordova
it will output something like this
/usr/local/bin/
then removing by
rm -rf /usr/local/bin/cordova
In a terminal put these:
cd C:\Program Files (x86)\Google\Chrome\Application
chrome.exe --disable-web-security --user-data-dir="c:/chromedev"
Just declare the variable at class or script scope, then access it from inside your methods or closures. Without an example, it's hard to be more specific for your particular problem though.
However, global variables are generally considered bad form.
Why not return the variable from one function, then pass it into the next?
Well you understood it partially. You have to tailor the beans according to your need and inform Spring container to manage it when required, by using a methodology populalrly known as IoC (Inversion of Control) coined by Martin Fowler, also known as Dependency Injection (DI).
You wire the beans in a way, so that you do not have to take care of the instantiating or evaluate any dependency on the bean. This is popularly known as Hollywood Principle.
Google is the best tool to explore more on this in addition to the links you would get flooded with here in this question. :)
Eclipse will never see a file until you force a refresh of the IDE. Its a feature! So you can put the file all over the project and Eclipse will ignore it completely and throw these errors. Hit refresh in Eclipse project view and then it works.
Simple java8 solution with capturing both outputs and reactive processing using CompletableFuture
:
static CompletableFuture<String> readOutStream(InputStream is) {
return CompletableFuture.supplyAsync(() -> {
try (
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
){
StringBuilder res = new StringBuilder();
String inputLine;
while ((inputLine = br.readLine()) != null) {
res.append(inputLine).append(System.lineSeparator());
}
return res.toString();
} catch (Throwable e) {
throw new RuntimeException("problem with executing program", e);
}
});
}
And the usage:
Process p = Runtime.getRuntime().exec(cmd);
CompletableFuture<String> soutFut = readOutStream(p.getInputStream());
CompletableFuture<String> serrFut = readOutStream(p.getErrorStream());
CompletableFuture<String> resultFut = soutFut.thenCombine(serrFut, (stdout, stderr) -> {
// print to current stderr the stderr of process and return the stdout
System.err.println(stderr);
return stdout;
});
// get stdout once ready, blocking
String result = resultFut.get();
The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203
First, I strongly recommend that you rename your variable list
to something else. list
is the name of the built-in list constructor, and you're hiding its normal function. I will rename list
to a
in the following.
Python names are references that are bound to objects. That means that unless you create more than one list, whenever you use a
it's referring to the same actual list object as last time. So when you call
listoflists.append((a, a[0]))
you can later change a
and it changes what the first element of that tuple points to. This does not happen with a[0]
because the object (which is an integer) pointed to by a[0]
doesn't change (although a[0]
points to different objects over the run of your code).
You can create a copy of the whole list a
using the list
constructor:
listoflists.append((list(a), a[0]))
Or, you can use the slice notation to make a copy:
listoflists.append((a[:], a[0]))
This post is regarding fetching only Distincts rows from Data table on basis of multiple Columns.
Public coid removeDuplicatesRows(DataTable dt)
{
DataTable uniqueCols = dt.DefaultView.ToTable(true, "RNORFQNo", "ManufacturerPartNo", "RNORFQId", "ItemId", "RNONo", "Quantity", "NSNNo", "UOMName", "MOQ", "ItemDescription");
}
You need to call this method and you need to assign value to datatable. In Above code we have RNORFQNo , PartNo,RFQ id,ItemId, RNONo, QUantity, NSNNO, UOMName,MOQ, and Item Description as Column on which we want distinct values.
just follow below steps:
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods
In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.
For a neat example have a look here.
And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.
Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods)
Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.
This is how I did this so that only one progress dialog can be open at a time. Based off of the answer from Suraj Bajaj
private ProgressDialog progress;
public void showLoadingDialog() {
if (progress == null) {
progress = new ProgressDialog(this);
progress.setTitle(getString(R.string.loading_title));
progress.setMessage(getString(R.string.loading_message));
}
progress.show();
}
public void dismissLoadingDialog() {
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
}
I also had to use
protected void onResume() {
dismissLoadingDialog();
super.onResume();
}
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
If you don't have a .gitignore file. You can create a new one by
touch .gitignore
And you can exclude a folder by entering the below command in the .gitignore file
/folderName
push this file into your git repository so that when a new person clone your project he don't have to add the same again
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="one">1</option>
<option name="2"value="two">2</option>
<option name="3"value="three"></option>
</select>
</body>
</html>
If someone is looking for a reversed list, like I was:
stuff = [1, 2, 3, 4]
def reverse(bla, y):
for subset in itertools.combinations(bla, len(bla)-y):
print list(subset)
if y != len(bla):
y += 1
reverse(bla, y)
reverse(stuff, 1)
No, this is not possible. In documents that make use of CSS, an inline style
attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:
The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:
declaration-list : S* declaration? [ ';' S* declaration? ]* ;
Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.
Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style
attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).
Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important
notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.
Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.
Try this:
String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
STEPS TO SOLVE THE ISSUE :-
Open the eclipse.ini file from your eclipse folder.
It has some of add on configuration . Find the line –launcher.XXMaxPermSize.It will be the last line in this file. Now remove/delete the the default value 256m and save it.
function SetCaretEnd(tID) {
tID += "";
if (!tID.startsWith("#")) { tID = "#" + tID; }
$(tID).focus();
var t = $(tID).val();
if (t.length == 0) { return; }
$(tID).val("");
$(tID).val(t);
$(tID).scrollTop($(tID)[0].scrollHeight); }
Install rubygems-update
gem install rubygems-update
update_rubygems
gem update --system
run this commands as root or use sudo.
Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.
One option is to replace table with CSS4 flex divs:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
That works in new browsers i.e. IE11+ see table at the bottom of the article.
above application.properties worked amazing for me:
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
let indexPathRow:Int = 0
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)
There is really no limit on the size of JSON data to be send or receive. We can send Json data in file too. According to the capabilities of browser that you are working with, Json data can be handled.
But why stop with MessageBox-specific implementation? Use the class below like this:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dg;
using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
{
dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
if (dg == DialogResult.No)
{
e.Cancel = true;
}
}
The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):
(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags
, which is below)
public class DialogCenteringService : IDisposable
{
private readonly IWin32Window owner;
private readonly HookProc hookProc;
private readonly IntPtr hHook = IntPtr.Zero;
public DialogCenteringService(IWin32Window owner)
{
if (owner == null) throw new ArgumentNullException("owner");
this.owner = owner;
hookProc = DialogHookProc;
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
}
private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(hHook);
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
public void Dispose()
{
UnhookWindowsHookEx(hHook);
}
private void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
if (!success)
{
return;
}
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(owner.Handle, ref recParent);
if (!success)
{
return;
}
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
//MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
}
// some p/invoke
// ReSharper disable InconsistentNaming
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
private const int WH_CALLWNDPROCRET = 12;
// ReSharper disable EnumUnderlyingTypeIsInt
private enum CbtHookAction : int
// ReSharper restore EnumUnderlyingTypeIsInt
{
// ReSharper disable UnusedMember.Local
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
// ReSharper restore UnusedMember.Local
}
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
// ReSharper restore InconsistentNaming
}
[Flags]
public enum SetWindowPosFlags : uint
{
// ReSharper disable InconsistentNaming
/// <summary>
/// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
/// </summary>
SWP_ASYNCWINDOWPOS = 0x4000,
/// <summary>
/// Prevents generation of the WM_SYNCPAINT message.
/// </summary>
SWP_DEFERERASE = 0x2000,
/// <summary>
/// Draws a frame (defined in the window's class description) around the window.
/// </summary>
SWP_DRAWFRAME = 0x0020,
/// <summary>
/// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
/// </summary>
SWP_FRAMECHANGED = 0x0020,
/// <summary>
/// Hides the window.
/// </summary>
SWP_HIDEWINDOW = 0x0080,
/// <summary>
/// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
/// </summary>
SWP_NOACTIVATE = 0x0010,
/// <summary>
/// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
/// </summary>
SWP_NOCOPYBITS = 0x0100,
/// <summary>
/// Retains the current position (ignores X and Y parameters).
/// </summary>
SWP_NOMOVE = 0x0002,
/// <summary>
/// Does not change the owner window's position in the Z order.
/// </summary>
SWP_NOOWNERZORDER = 0x0200,
/// <summary>
/// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
/// </summary>
SWP_NOREDRAW = 0x0008,
/// <summary>
/// Same as the SWP_NOOWNERZORDER flag.
/// </summary>
SWP_NOREPOSITION = 0x0200,
/// <summary>
/// Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
/// </summary>
SWP_NOSENDCHANGING = 0x0400,
/// <summary>
/// Retains the current size (ignores the cx and cy parameters).
/// </summary>
SWP_NOSIZE = 0x0001,
/// <summary>
/// Retains the current Z order (ignores the hWndInsertAfter parameter).
/// </summary>
SWP_NOZORDER = 0x0004,
/// <summary>
/// Displays the window.
/// </summary>
SWP_SHOWWINDOW = 0x0040,
// ReSharper restore InconsistentNaming
}
Android SDK build tools are used to debug, build, run and test an Android application.
Android Build Tools can be used to develop and work from command line or IDE (i.e Eclipse or Android Studio).
Also used to connect Android devices and root them.(fastboot, adb and more..)
Always use the latest.(Recommended)
You make the http request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
You read the Buffer
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();
Create a JSONObject and pass the result string to the constructor:
JSONObject json = new JSONObject(result);
Parse the json results to your desired variables:
String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");
Do not forget to import:
import org.json.JSONObject;
The linked comment is incorrect : 'L' to '1' will produce a rising edge.
In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk)
will (correctly) not trigger while (clk'event and clk = '1')
(incorrectly) will.
Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.
If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:
Go to the RabbitMQ command prompt.
Type:
rabbitmq-plugins enable rabbitmq_management
You cannot put comments inside UWP XAML tags. Your syntax is right.
TO DO:
<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
<!-- Cool comment -->
NOT TO DO:
<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
This worked for me:
dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();
I think you did like this:
<asp:Content ID="Content2" ContentPlaceHolderID="MasterContent" runat="server">
<form id="form1" runat="server">
</form>
</asp:Content>
The form tag isn't needed. because you already have the same tag in the master page.
So you just remove that and it should be working.
Uninstalling and re-installing the NuGet package worked for me.
Execute this in the Package Manager Console:
UnInstall-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.
Ctrl + Enter - as simple as that!
This, for many people, will be better than autocompleting on everything.
The arguments that you provide to a bashscript will appear in the variables $1
and $2
and $3
where the number refers to the argument. $0
is the command itself.
The arguments are seperated by spaces, so if you would provide the -from
and -to
in the command, they will end up in these variables too, so for this:
./ocrscript.sh -from /home/kristoffer/test.png -to /home/kristoffer/test.txt
You'll get:
$0 # ocrscript.sh
$1 # -from
$2 # /home/kristoffer/test.png
$3 # -to
$4 # /home/kristoffer/test.txt
It might be easier to omit the -from
and the -to
, like:
ocrscript.sh /home/kristoffer/test.png /home/kristoffer/test.txt
Then you'll have:
$1 # /home/kristoffer/test.png
$2 # /home/kristoffer/test.txt
The downside is that you'll have to supply it in the right order. There are libraries that can make it easier to parse named arguments on the command line, but usually for simple shell scripts you should just use the easy way, if it's no problem.
Then you can do:
/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1
The double quotes around the $1
and the $2
are not always necessary but are adviced, because some strings won't work if you don't put them between double quotes.
you need to enable the Show Assistant Editor:
It can be used to use features which will appear in newer versions while having an older release of Python.
For example
>>> from __future__ import print_function
will allow you to use print
as a function:
>>> print('# of entries', len(dictionary), file=sys.stderr)
My firewall was blocking post 3307 which my MySQL listening on. So I changed port from 3307 to 3306.Then I can successfully connect to a database.
I had the same issue, docker-compose was creating a directory instead of a file, then crashing mid-way.
what i did :
run the container without mapping the file
copy the config file to the host location :
docker cp containername:/var/www/html/config.php ./config.php
remove the container (docker-compose down)
put the mapping back and remount up the container
docker compose will find the config file, and will map that instead of trying to create a directory.
(1)
ArrayList<Object> list = new ArrayList <>();`
list.add("ddd");
list.add(2);
list.add(11122.33);
System.out.println(list);
(2)
ArrayList arraylist = new ArrayList();
arraylist.add(5);
arraylist.add("saman");
arraylist.add(4.3);
System.out.println(arraylist);
When I installed Cassandra 3.11.1, I came across this problem. I checked the /var/log/cassandra/cassandra.log and found this error Exception encountered during startup....It is a bug and already reported. The original post link https://issues.apache.org/jira/browse/CASSANDRA-14173.
The solution is to downgrade Cassandra to 3.0
curl -O https://www.apache.org/dist/cassandra/redhat/30x/cassandra-3.0.15-1.noarch.rpm
or
wget https://www.apache.org/dist/cassandra/redhat/30x/cassandra-3.0.15-1.noarch.rpm
cassandra (pid 2322) is running...
I fixed it by removing float:left
, and adding display:inline-block
instead. Haven't used it for images, but should work fine, there, too.
In PyCharm 2020.1 CE and Professional, you can add a path to your project's Python interpreter by doing the following:
1) Click the interpreter in the bottom right corner of the project and select 'Interpreter Settings'
2) Click the settings button to the right of the interpreter name and select 'Show All':
3) Make sure your project's interpreter is selected and click the fifth button in the bottom toolbar, 'show paths for the selected interpreter':
4) Click the '+' button in the bottom toolbar and add a path to the folder containing your module:
I was seeing this error along with: "Error:compileSdkVersion android-21 requires compiling with JDK 7"
For me, the solution was found here, where I had to update the JDK location in the project structure.
I did not have the upstream branch on my local git. I had created a local branch from master, git checkout -b mybranch . I created a branch with bitbucket GUI on the upstream git and pushed my local branch (mybranch) to that upstream branch. Once I did a git fetch on my local git to retrieve the upstream branch, I could do a git branch -d mybranch.
use the below line
e2.setSelection(e2.length());
e2
is edit text Object Name
Perhaps the error message is somewhat misleading, but the gist is that X_train
is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]
update - modify existent only. To avoid side effect of indexer use:
int val;
if (dic.TryGetValue(key, out val))
{
// key exist
dic[key] = val;
}
update or (add new if value doesn't exist in dic)
dic[key] = val;
for instance:
d["Two"] = 2; // adds to dictionary because "two" not already present
d["Two"] = 22; // updates dictionary because "two" is now present
After struggling myself with this I found a solution that works just replace the $ with jQueryjQuery.fancybox.close()
and I made it an inline script on an onClick. Going to check if i can call it from the parent
In the case you have different sample sizes, it may be difficult to compare the distributions with a single y-axis. For example:
import numpy as np
import matplotlib.pyplot as plt
#makes the data
y1 = np.random.normal(-2, 2, 1000)
y2 = np.random.normal(2, 2, 5000)
colors = ['b','g']
#plots the histogram
fig, ax1 = plt.subplots()
ax1.hist([y1,y2],color=colors)
ax1.set_xlim(-10,10)
ax1.set_ylabel("Count")
plt.tight_layout()
plt.show()
In this case, you can plot your two data sets on different axes. To do so, you can get your histogram data using matplotlib, clear the axis, and then re-plot it on two separate axes (shifting the bin edges so that they don't overlap):
#sets up the axis and gets histogram data
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist([y1, y2], color=colors)
n, bins, patches = ax1.hist([y1,y2])
ax1.cla() #clear the axis
#plots the histogram data
width = (bins[1] - bins[0]) * 0.4
bins_shifted = bins + width
ax1.bar(bins[:-1], n[0], width, align='edge', color=colors[0])
ax2.bar(bins_shifted[:-1], n[1], width, align='edge', color=colors[1])
#finishes the plot
ax1.set_ylabel("Count", color=colors[0])
ax2.set_ylabel("Count", color=colors[1])
ax1.tick_params('y', colors=colors[0])
ax2.tick_params('y', colors=colors[1])
plt.tight_layout()
plt.show()
By combining all of these answer here and small changes that I made, I think this function would be useful. its safe, quick, easily maintainable.
def deep_get(dictionary, keys, default=None):
return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
Example :
>>> from functools import reduce
>>> def deep_get(dictionary, keys, default=None):
... return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
...
>>> person = {'person':{'name':{'first':'John'}}}
>>> print (deep_get(person, "person.name.first"))
John
>>> print (deep_get(person, "person.name.lastname"))
None
>>> print (deep_get(person, "person.name.lastname", default="No lastname"))
No lastname
>>>
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
I use this to get the Parent, similarly for child
$( this ).children( 'li.target' ).css("border", "3px double red");
Good Luck
ToggleImageButton
which implements Checkable
interface and supports OnCheckedChangeListener
and android:checked
xml attribute:
public class ToggleImageButton extends ImageButton implements Checkable {
private OnCheckedChangeListener onCheckedChangeListener;
public ToggleImageButton(Context context) {
super(context);
}
public ToggleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
setChecked(attrs);
}
public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChecked(attrs);
}
private void setChecked(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
a.recycle();
}
@Override
public boolean isChecked() {
return isSelected();
}
@Override
public void setChecked(boolean checked) {
setSelected(checked);
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checked);
}
}
@Override
public void toggle() {
setChecked(!isChecked());
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
}
}
res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleImageButton">
<attr name="android:checked" />
</declare-styleable>
</resources>
You can use scalar multiplication to modify each element in your vector.
> r <- 0:10
> r <- r * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
or
> r <- 0:10 * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
To stage modified and deleted files
git add -u
The way I solved it is by setting the AVD memory limit and HAXM memory to be equal in size which is 1 GB = 1024 MB. The AVD cannot have higher memory limit than the HAXM.
1. Setting the HAXM memory to be 1024 M
The only way to change the HAXM memory is by installing it again. I did it using the terminal. Locate Hardware_Accelerated_Execution_Manager in your machine. Then change directory that folder to run the installation script.
cd ~/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager
-OR-
cd ~/Library/Developer/Xamarin/android-sdk-macosx/extras/intel/Hardware_Accelerated_Execution_Manager
May need to change permissions:
sudo chmod 755 "HAXM installation"
Then:
./HAXM\ installation -m 1024
-OR-
sudo ./"HAXM installation" -m 1024
2. Setting the virtual device the same size with HAXM memory limit
This works for me. Good luck!
Changing the above options form Help menu didn't work for me. You have edit idea.properties file and change to some large no.
MAC: /Applications/<Android studio>.app/Contents/bin[Open App contents]
Idea.max.intellisense.filesize=999999
WINDOWS: IDE_HOME\bin\idea.properties
I think this code is not so bad.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.whiteColor()
headerView.backgroundView = backgroundView
headerView.textLabel.text = "hello"
return headerView
}
I believe that specifying version works only for git-endpoints. And not for folder/zip ones. As when you point bower to a js-file/folder/zip you already specified package and version (except for js indeed). Because a package has bower.json with version in it. Specifying a version in 'bower install' makes sense when you're pointing bower to a repository which can have many versions of a package. It can be only git I think.
How about checking with python
code:
from tensorflow.python.platform import build_info as tf_build_info
print(tf_build_info.cudnn_version_number)
# 7 in v1.10.0
It's as simple as this: lambda is a language construct, i.e. simply syntax for anonymous functions; a closure is a technique to implement it -- or any first-class functions, for that matter, named or anonymous.
More precisely, a closure is how a first-class function is represented at runtime, as a pair of its "code" and an environment "closing" over all the non-local variables used in that code. This way, those variables are still accessible even when the outer scopes where they originate have already been exited.
Unfortunately, there are many languages out there that do not support functions as first-class values, or only support them in crippled form. So people often use the term "closure" to distinguish "the real thing".
It's much easier to do like this:
if(!$('#foo').hasClass('bar')) {
...
}
The ! in front of the criteria means false, works in most programming languages.
I realise this is an old thread, but for anyone who's interested in looking at this from a purely mathematical perspective, there's an excellent thread on the maths stack exchange, here:
https://math.stackexchange.com/questions/190111/how-to-check-if-a-point-is-inside-a-rectangle
Edit: Inspired by this thread, I've put together a simple vector method for quickly determining where your point lies.
Suppose you have a rectangle with points at p1 = (x1, y1), p2 = (x2, y2), p3 = (x3, y3) and p4 = (x4, y4), going clockwise. If a point p = (x, y) lies inside the rectangle, then the dot product (p - p1).(p2 - p1) will lie between 0 and |p2 - p1|^2, and (p - p1).(p4 - p1) will lie between 0 and |p4 - p1|^2. This is equivalent to taking the projection of the vector p - p1 along the length and width of the rectangle, with p1 as the origin.
This may make more sense if I show an equivalent code:
p21 = (x2 - x1, y2 - y1)
p41 = (x4 - x1, y4 - y1)
p21magnitude_squared = p21[0]^2 + p21[1]^2
p41magnitude_squared = p41[0]^2 + p41[1]^2
for x, y in list_of_points_to_test:
p = (x - x1, y - y1)
if 0 <= p[0] * p21[0] + p[1] * p21[1] <= p21magnitude_squared:
if 0 <= p[0] * p41[0] + p[1] * p41[1]) <= p41magnitude_squared:
return "Inside"
else:
return "Outside"
else:
return "Outside"
And that's it. It will also work for parallelograms.
Long answer:
Floating-point numbers have three components:
Essentially, this works out to sign * 2^exponent * (1 + fraction)
. The “size”
of the number, it’s exponent, is irrelevant to us, because it only scales the
value of the fraction portion. Knowing that log10(n)
gives the number of
digits of n
,† we can determine the precision of a floating point number
with log10(largest_possible_fraction)
. Because each bit in a float stores 2
possibilities, a binary number of n
bits can store a number up to 2n - 1
(a
total of 2n
values where one of the values is zero). This gets a bit
hairier, because it turns out that floating point numbers are stored with one
less bit of fraction than they can use, because zeroes are represented specially
and all non-zero numbers have at least one non-zero binary bit.‡
Combining this, the digits of precision for a floating point number is
log10(2n)
, where n
is the number of bits of the floating point number’s
fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of
precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits
of precision.
For more on floating point accuracy, you might want to read about the concept of a machine epsilon.
† For n = 1
at least — for other numbers your formula will look more like
?log10(|n|)? + 1
.
‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
Parse the dates and compare them as you would numbers:
function isLater(str1, str2)
{
return new Date(str1) > new Date(str2);
}
If you need to support other date format consider a library such as date.js.
Its simple matter of setting adjustViewBounds="true"
and scaleType="fitCenter"
in the XML file for the ImageView!
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/image"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
/>
Note: layout_width
is set to match_parent
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
Normally there's no need for that. First of all
echo $CLASSPATH
If there's something in there, you probably want to check Applications -> Utilites -> Java.
abc = "2018-06-16 04:45:18.68"
filename = "abc.txt"
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if abc in line:
lastline = num
print "last occurance of work at file is in "+str(lastline)
You can dynamically change color of any items ( layout, textview ) . Try below code to set color programmatically in layout
in activity.java file
String quote_bg_color = "#FFC107"
quoteContainer= (LinearLayout)view.findViewById(R.id.id_quotecontainer);
quoteContainer.setBackgroundResource(R.drawable.layout_round);
GradientDrawable drawable = (GradientDrawable) quoteContainer.getBackground();
drawable.setColor(Color.parseColor(quote_bg_color));
create layout_round.xml in drawable folder
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorPrimaryLight"/>
<stroke android:width="0dp" android:color="#B1BCBE" />
<corners android:radius="10dp"/>
<padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>
layout in activity.xml file
<LinearLayout
android:id="@+id/id_quotecontainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
----other components---
</LinearLayout>
If you're using Windows 10, as I am, and the port is occupied by Microsoft-IIS/10.0, change the lines 62 and 63, of the httpd.conf
, from:
Listen 0.0.0.0:80
Listen [::0]:80
To:
Listen 0.0.0.0:8080
Listen [::0]:8080
As the people here suggested.
And also, change the line 221, from:
ServerName localhost:80
To:
ServerName localhost:8080
Now, your host will be available at http://localhost:8080/.
Try like this
<script>
$(document).ready(function(){
$("#order_ship_date").datepicker({
changeMonth:true,
changeYear:true,
dateFormat:"yy-mm-dd",
minDate: +2,
});
});
</script>
html code is given below
<input id="order_ship_date" type="text" class="input" style="width:80px;" />
I would solve it by doing:
private void button1_Click(object sender, EventArgs e)
{
Form2 m = new Form2();
m.Show();
Form1 f = new Form1();
this.Visible = false;
this.Hide();
}
a:not([href]) { cursor: pointer; }
In my case,
My application is developed in MVC
and my home controller class was decorated with [Authorize]
which was causing this issue.
So I've removed it because my application don't require any authentication.
ul, li {_x000D_
list-style: none;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
ul {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
width: calc(100% / 3);_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 100%;_x000D_
height: auto;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
<br> Line 2_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
<br> Line 2_x000D_
<br> Line 3_x000D_
<br> Line 4_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
<br> Line 1_x000D_
<br> Line 2_x000D_
</li>_x000D_
</ul>
_x000D_
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
Take a clone of a remote repository and run git branch -a
(to show all the branches git knows about). It will probably look something like this:
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
Here, master
is a branch in the local repository. remotes/origin/master
is a branch named master
on the remote named origin
. You can refer to this as either origin/master
, as in:
git diff origin/master..master
You can also refer to it as remotes/origin/master
:
git diff remotes/origin/master..master
These are just two different ways of referring to the same thing (incidentally, both of these commands mean "show me the changes between the remote master
branch and my master
branch).
remotes/origin/HEAD
is the default branch
for the remote named origin
. This lets you simply say origin
instead of origin/master
.
Here is another method to get date
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
vueObject.$forceUpdate();
why don't you use forceUpdate method?
Here's what I found.
stop:
schtasks /end /s <machine name> /tn <task name>
start:
schtasks /run /s <machine name> /tn <task name>
C:\>schtasks /?
SCHTASKS /parameter [arguments]
Description:
Enables an administrator to create, delete, query, change, run and
end scheduled tasks on a local or remote system. Replaces AT.exe.
Parameter List:
/Create Creates a new scheduled task.
/Delete Deletes the scheduled task(s).
/Query Displays all scheduled tasks.
/Change Changes the properties of scheduled task.
/Run Runs the scheduled task immediately.
/End Stops the currently running scheduled task.
/? Displays this help message.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
You can give whatever name you want.
Styles guides are recommendations and not musts.
But you have to care to use everywhere the same name.
For example for Test_Model you have to:
class Test_Model extends CI_Model
Test_Model.php
$this->load->model('Test_Model');
$this->Test_Model
To avoid using hard coding strings you can load model like this:
$this->load->model(Test_Model::class);
You could alter the figsize
by passing a tuple
showing the width, height
parameters you would like to keep.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
EDIT
I remember answering a similar question of yours where you had to set the index as TIMESTAMP
. So, you could then do something like below:
df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)
For the head
of the dataframe you posted, the plot would look like:
svn checkout --force svn://repo website.dir
then
svn revert -R website.dir
Will check out on top of existing files in website.dir, but not overwrite them. Then the revert will overwrite them. This way you do not need to take the site down to complete it.
@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
List<String> tables = new ArrayList<String>();
String db = "";
while (rs.next()) {
tables.add(rs.getString(3));
db = rs.getString(1);
}
List<String> database = new ArrayList<String>();
database.add(db);
databaseTables.put("database", database);
Collections.reverse(tables);
databaseTables.put("tables", tables);
return new ObjectMapper().writeValueAsString(databaseTables);
}
@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{
System.out.println("...tablename......"+tablename);
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
Statement st = con.createStatement();
String sql = "select * from "+tablename;
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
HashMap<String,String> columnDetails = new HashMap<String,String>();
for (int i = 0; i < rowCount; i++) {
columnDetails = new HashMap<String,String>();
Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
method.setAccessible(true);
com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
columnDetails.put("columnColl", field.getCollation());
columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
if (field.isPrimaryKey()) {
columnDetails.put("columnKEY", "PRI");
} else if(field.isMultipleKey()) {
columnDetails.put("columnKEY", "MUL");
} else if(field.isUniqueKey()) {
columnDetails.put("columnKEY", "UNI");
} else {
columnDetails.put("columnKEY", "");
}
columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
databaseColumns.add(columnDetails);
}
HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
Collections.reverse(databaseColumns);
tableColumns.put("columns", databaseColumns);
return new ObjectMapper().writeValueAsString(tableColumns);
}
dt.AsEnumerable()
.GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] })
.Select(g =>
{
var row = dt.NewRow();
row["PK"] = g.Min(r => r.Field<int>("PK"));
row["Col1"] = g.Key.Col1;
row["Col2"] = g.Key.Col2;
return row;
})
.CopyToDataTable();
If you want to match the two words in either order, use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'
If Failed always comes after VendorEnquiry on the line, just use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'
Python Counter is also a good option in this case:
from collections import Counter
counter = Counter(["Sachin Tendulkar", "Sachin Tendulkar", "other things"])
print(counter)
This returns a dict with the count of each element in the list:
Counter({'Sachin Tendulkar': 2, 'other things': 1})
The current "pipable" variant of this operator is called finalize()
(since RxJS 6). The older and now deprecated "patch" operator was called finally()
(until RxJS 5.5).
I think finalize()
operator is actually correct. You say:
do that logic only when I subscribe, and after the stream has ended
which is not a problem I think. You can have a single source
and use finalize()
before subscribing to it if you want. This way you're not required to always use finalize()
:
let source = new Observable(observer => {
observer.next(1);
observer.error('error message');
observer.next(3);
observer.complete();
}).pipe(
publish(),
);
source.pipe(
finalize(() => console.log('Finally callback')),
).subscribe(
value => console.log('#1 Next:', value),
error => console.log('#1 Error:', error),
() => console.log('#1 Complete')
);
source.subscribe(
value => console.log('#2 Next:', value),
error => console.log('#2 Error:', error),
() => console.log('#2 Complete')
);
source.connect();
This prints to console:
#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message
Jan 2019: Updated for RxJS 6
You won't find anything overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE.
For a Linux alternative, try DDD if free software is your thing.
Vim requires the cursor to be in the current screen at all times, however, you could bookmark the current position scroll around and then return to where you were.
mg # This book marks the current position as g (this can be any letter)
<scroll around>
`g # return to g
select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)
You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.
This will display PDF, DOC and DOCX filetypes.
Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues
Note, the localhost is a special string that FB allows here. If you didn't configure your debugging environment under localhost, you'll have to push it underneath that name as far as I can tell.
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
If you are looking to copy all the text files in one folder to merge and copy to another folder, you can do this to achieve that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace HowToCopyTextFiles
{
class Program
{
static void Main(string[] args)
{
string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}
}
}
}
spring.jpa.hibernate.ddl-auto = update
change update
to create
, and run it
after run safely again change create
to update
so again all tables will not create and you can use your previous data
DECLARE @MyList TABLE (Value INT)
INSERT INTO @MyList VALUES (1)
INSERT INTO @MyList VALUES (2)
INSERT INTO @MyList VALUES (3)
INSERT INTO @MyList VALUES (4)
SELECT *
FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)
Login in with System Admin User Account and execute below SQL Procedure.
begin
dbms_xdb.sethttpport('Your Port Number');
end;
Then open the Browser and access the below URL
As part of the uuid spec, if you generate a uuid from random it must contain a "4" as the 13th character and a "8", "9", "a", or "b" in the 17th (source).
// this makes sure that the 13th character is "4"
u[6] = (u[6] | 0x40) & 0x4F
// this makes sure that the 17th is "8", "9", "a", or "b"
u[8] = (u[8] | 0x80) & 0xBF
According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.
public class MyCustomClass extends YourAbstractClass {
/// attributes, methods ,...
}
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
There are two problems with your xpath - first you need to remove the child selector from after Data
like phihag mentioned. Also you forgot to include root
in your xpath. Here is what you want to do:
select="/root/DataSet/Data[@Value1='2']/@Value2"
I fount it's here it working fine.
var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
var d = new Date();
var hour = d.getHours(); /* Returns the hour (from 0-23) */
var minutes = d.getMinutes(); /* Returns the minutes (from 0-59) */
var result = hour;
var ext = '';
if(date_format == '12'){
if(hour > 12){
ext = 'PM';
hour = (hour - 12);
result = hour;
if(hour < 10){
result = "0" + hour;
}else if(hour == 12){
hour = "00";
ext = 'AM';
}
}
else if(hour < 12){
result = ((hour < 10) ? "0" + hour : hour);
ext = 'AM';
}else if(hour == 12){
ext = 'PM';
}
}
if(minutes < 10){
minutes = "0" + minutes;
}
result = result + ":" + minutes + ' ' + ext;
console.log(result);
and plunker example here
I just tried and it works with require "./tokenizer"
. Hope this helps.
"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.
Declaration: java.lang.Object.toString()
Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.
Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );
You can find the complete code here. You can test the code here.
I landed here looking for a solution for the case where I dont use data binding. Nothing worked for me but I got it in the end with:
dataGridView.Columns.Clear();
dataGridView.Rows.Clear();
dataGridView.Refresh();
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
Take a look at Linq-to-Excel. It's pretty neat.
var book = new LinqToExcel.ExcelQueryFactory(@"File.xlsx");
var query =
from row in book.Worksheet("Stock Entry")
let item = new
{
Code = row["Code"].Cast<string>(),
Supplier = row["Supplier"].Cast<string>(),
Ref = row["Ref"].Cast<string>(),
}
where item.Supplier == "Walmart"
select item;
It also allows for strongly-typed row access too.
public function testException() {
try {
$this->methodThatThrowsException();
$this->fail("Expected Exception has not been raised.");
} catch (Exception $ex) {
$this->assertEquals($ex->getMessage(), "Exception message");
}
}
The following commands will work well for ruby on rails application deployment on heroku if heroku is already installed on developers machine. # indicates a comment
There's a sed option too...
sed 's/\([^ ]*\) \(.*\)/\2 \1/' inputfile.txt
Explained...
Swap
\([^ ]*\) = Match anything until we reach a space, store in $1
\(.*\) = Match everything else, store in $2
With
\2 = Retrieve $2
\1 = Retrieve $1
More thoroughly explained...
s = Swap
/ = Beginning of source pattern
\( = start storing this value
[^ ] = text not matching the space character
* = 0 or more of the previous pattern
\) = stop storing this value
\( = start storing this value
. = any character
* = 0 or more of the previous pattern
\) = stop storing this value
/ = End of source pattern, beginning of replacement
\2 = Retrieve the 2nd stored value
\1 = Retrieve the 1st stored value
/ = end of replacement
Customer findCustomerByid(int id){
for (int i=0; i<this.customers.size(); i++) {
Customer customer = this.customers.get(i);
if (customer.getId() == id){
return customer;
}
}
return null; // no Customer found with this ID; maybe throw an exception
}
public char lastChar(String s) {
if (s == "" || s == null)
return ' ';
char lc = s.charAt(s.length() - 1);
return lc;
}
When you install python for Windows, use the standard option or install everything it asks. I got the error because I deselected tcl.
Assign an id or a class for your tbody.
document.querySelector("#tbodyId").remove();
document.querySelectorAll(".tbodyClass").remove();
You can name your id or class how you want, not necessarily #tbodyId
or .tbodyClass
.
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
Following are the some approaches for underlined text in android:
1st Approach
You can define your string in strings.xml
<string name="your_string"><u>Underlined text</u></string>
And use that string in your xml
file
<TextView
android:id="@+id/txt_underlined"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/your_string"/>
Or you can use that string in your Activity/Fragment
txtView.setText(R.string.your_string);
2nd Approach
To underline the text in TextView, you can use SpannableString
String text="Underlined Text";
SpannableString content = new SpannableString(text);
content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
txtView.setText(content);
3rd Approach
You can make use of setPaintFlags method of TextView to underline the text of TextView.
txtView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
txtView.setText("Underlined Text");
4th Approach
Make use of Html.fromHtml(htmlString)
;
String htmlString="<u>Underlined Text</u>";
txtView.setText(Html.fromHtml(htmlString));
Or
txtView.setText(Html.fromHtml("<u>underlined</u> text"));
Note:
If you have added this line android:textAllCaps="true"
in your layout, then none of the above will work. For that, you have to define your string in Caps and then any of the above approach.
The shortest code
ChromeDriver drv = new ChromeDriver();
drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");
drv.ExecuteScript("return alert(document.title);");
I think "disabled" excludes the input from being sent on the POST
You can't cast a base object to a derived type - it isn't of that type.
If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:
DerivedType D;
BaseType B;
BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type
DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL
string.Format("{0:hh:mm:ss tt}", DateTime.Now)
This should give you the string value of the time. tt should append the am/pm.
You can also look at the related topic:
This is the regex I use to remove duplicate phrases in my twitch bot:
(\S+\s*)\1{2,}
(\S+\s*)
looks for any string of characters that isn't whitespace, followed whitespace.
\1{2,}
then looks for more than 2 instances of that phrase in the string to match. If there are 3 phrases that are identical, it matches.
Double precision means the numbers takes twice the word-length to store. On a 32-bit processor, the words are all 32 bits, so doubles are 64 bits. What this means in terms of performance is that operations on double precision numbers take a little longer to execute. So you get a better range, but there is a small hit on performance. This hit is mitigated a little by hardware floating point units, but its still there.
The N64 used a MIPS R4300i-based NEC VR4300 which is a 64 bit processor, but the processor communicates with the rest of the system over a 32-bit wide bus. So, most developers used 32 bit numbers because they are faster, and most games at the time did not need the additional precision (so they used floats not doubles).
All three systems can do single and double precision floating operations, but they might not because of performance. (although pretty much everything after the n64 used a 32 bit bus so...)
type FunctionName = (n: inputType) => any;
class ClassName {
save(callback: FunctionName) : void {
callback(data);
}
}
This surely aligns with the functional programming paradigm.
I just had this problem. For me the reason was deleting a CoreData managed object ans trying to read it afterwards from another place.
if ($string =~ m/something/) {
# Do work
}
Where something
is a regular expression.
The right way to do this is with the spy on property, it will allow you to simulate a property on an object with an specific value.
const spy = spyOnProperty(myObj, 'valueA').and.returnValue(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();
In my case, it was due to an IP address that Apache is listening to. Previously I have set it to 192.168.10.6 and recently Apache service is not running. I noticed that due to My laptop wifi changed recently and new IP is different. After fixing the wifi IP to laptop previous IP, Apache service is running again without any error.
Also if you don't want to change wifi IP then remove/comment that hardcode IP in httpd.conf file to resolve conflict.
Maybe the sample is oversimplified, but you don't need the Java stream API here. Just use the Map directly.
List<String> list1 = id1.get(1); // this will return the list from your map
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
It seems that the problem is in eslint-plugin-react
.
It can not correctly detect what props were mentioned in propTypes
if you have annotated named objects via destructuring anywhere in the class.
There was similar problem in the past
A simple ES6 way to get both the first key and remaining parts in a string would be:
const [key, ...rest] = "good_luck_buddy".split('_')
const value = rest.join('_')
console.log(key, value) // good, luck_buddy
This steps will delete all topics and data
The key here is to visualise the call tree. Once done that, the complexity is:
nodes of the call tree * complexity of other code in the function
the latter term can be computed the same way we do for a normal iterative function.
Instead, the total nodes of a complete tree are computed as
C^L - 1
------- , when C>1
/ C - 1
/
# of nodes =
\
\
L , when C=1
Where C is number of children of each node and L is the number of levels of the tree (root included).
It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".
So, in the examples above:
n level 1 n-1 level 2 n-2 level 3 n-3 level 4 ... ~ n levels -> L = n
n n-5 n-10 n-15 ... ~ n/5 levels -> L = n/5
n n/5 n/5^2 n/5^3 ... ~ log5(n) levels -> L = log5(n)
n level 1 n-1 n-1 level 2 n-2 n-2 n-2 n-2 ... n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3 ... ... ~ n levels -> L = n
n n-5 n-10 n-15 ... ~ n/5 levels -> L = n/5
That would be the tempfile module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
For completeness, here's how it searches for the temporary directory, according to the documentation:
TMPDIR
environment variable.TEMP
environment variable.TMP
environment variable.Wimp$ScrapDir
environment variable.C:\TEMP
, C:\TMP
, \TEMP
, and \TMP
, in that order./tmp
, /var/tmp
, and /usr/tmp
, in that order.javascript fade to white without jQuery or other library:
<div id="x" style="background-color:rgb(255,255,105)">hello world</div>
<script type="text/javascript">
var gEvent=setInterval("toWhite();", 100);
function toWhite(){
var obj=document.getElementById("x");
var unBlue=10+parseInt(obj.style.backgroundColor.split(",")[2].replace(/\D/g,""));
if(unBlue>245) unBlue=255;
if(unBlue<256) obj.style.backgroundColor="rgb(255,255,"+unBlue+")";
else clearInterval(gEvent)
}
</script>
In printing, yellow is minus blue, so starting with the 3rd rgb element (blue) at less than 255 starts out with a yellow highlight. Then the 10+
in setting the var unBlue
value increments the minus blue until it reaches 255.
You can also move mounted
out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.
function init() {
// Use `this` normally
}
new Vue({
methods:{
init
},
mounted(){
init.call(this)
}
})
You must have a server-side script to handle your request, it can't be done using javascript.
To send raw data without URIencoding or escaping special characters to the php and save it as new txt
file you can send ajax request using post
method and FormData
like:
JS:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
PHP:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
Edit:
As Florian mentioned below, the XHR fallback is not required since FormData
is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:
var xhr = new XMLHttpRequest();
Also please note that this works only for browsers that support FormData
such as IE +10.
Well, the straightforward method is to create an appropriate class/structure which holds all your parameter values and pass that to the thread.
Another solution in VB10 is to use the fact that lambdas create a closure, which basically means the compiler doing the above automatically for you:
Dim evaluator As New Thread(Sub()
testthread(goodList, 1)
End Sub)
Adding library in Android studio 2.1
Just Go to project -> then it has some android,package ,test ,project view
Just change it to Project View
under the app->lib folder
you can directly copy paste the lib and do android synchronize it.
That's it
Some *nix standard util one-liners, no temp files needed. NB: the OP wanted an efficient fix, (i.e. faster), and the top answers are usually faster than this answer. These one-liners are for those who like *nix software tools, for whatever reasons. In rare cases, (e.g. scarce IO & memory), these snippets can actually be faster than some of the top answers.
Call the input file foo.
If we know foo has four columns:
for f in 1 2 3 4 ; do cut -d ' ' -f $f foo | xargs echo ; done
If we don't know how many columns foo has:
n=$(head -n 1 foo | wc -w)
for f in $(seq 1 $n) ; do cut -d ' ' -f $f foo | xargs echo ; done
xargs
has a size limit and therefore would make incomplete work with a long file. What size limit is system dependent, e.g.:
{ timeout '.01' xargs --show-limits ; } 2>&1 | grep Max
Maximum length of command we could actually use: 2088944
tr
& echo
:
for f in 1 2 3 4; do cut -d ' ' -f $f foo | tr '\n\ ' ' ; echo; done
...or if the # of columns are unknown:
n=$(head -n 1 foo | wc -w)
for f in $(seq 1 $n); do
cut -d ' ' -f $f foo | tr '\n' ' ' ; echo
done
Using set
, which like xargs
, has similar command line size based limitations:
for f in 1 2 3 4 ; do set - $(cut -d ' ' -f $f foo) ; echo $@ ; done
Received this error while using the openAM Fedlet on IIS7
Changing the user account for the default website resolved the issue. Ideally, you would want this to be a service account. Perhaps even the IUSR account. Suggest looking up methods for IIS hardening to nail it down completely.
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
Another MySQL option that may look more like Oracle's DECODE
is a combination of FIELD
and ELT
. In the code that follows, FIELD()
returns the argument list position of the string that matches Age. ELT()
returns the string from ELT
s argument list at the position provided by FIELD()
. For example, if Age
is 14
, FIELD(Age, ...)
returns 2
because 14
is the 2nd argument of FIELD
(not counting Age
). Then, ELT(2, ...)
returns 'Fourteen'
, which is the 2nd argument of ELT
(not counting the FIELD()
argument). IFNULL
returns the default AgeBracket
if no match to Age
is found in the list.
Select Name, IFNULL(ELT(FIELD(Age,
13, 14, 15, 16, 17, 18, 19),'Thirteen','Fourteen','Fifteen','Sixteen',
'Seventeen','Eighteen','Nineteen'),
'Adult') AS AgeBracket
FROM Person
While I don't think this is the best solution to the question either in terms of performance or readability it is interesting as an exploration of MySQL's string functions. Keep in mind that FIELD
's output does not seem to be case sensitive. I.e., FIELD('A','A')
and FIELD('a','A')
both return 1
.
Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.
>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}
You can use regular expressions for this purpose, but it's good to avoid extra exceptions when input string mismatches against regular expression.
First to avoid extra headache of escaping to regex pattern - we could just use function for that purpose:
String reStrEnding = Regex.Escape("-");
I know that this does not do anything - as "-" is the same as Regex.Escape("=") == "="
, but it will make difference for example if character is @"\"
.
Then we need to match from begging of the string to string ending, or alternately if ending is not found - then match nothing. (Empty string)
Regex re = new Regex("^(.*?)" + reStrEnding);
If your application is performance critical - then separate line for new Regex, if not - you can have everything in one line.
And finally match against string and extract matched pattern:
String matched = re.Match(str).Groups[1].ToString();
And after that you can either write separate function, like it was done in another answer, or write inline lambda function. I've wrote now using both notations - inline lambda function (does not allow default parameter) or separate function call.
using System;
using System.Text.RegularExpressions;
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
}
}
class Program
{
static void Main(string[] args)
{
Regex re = new Regex("^(.*?)-");
Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };
Console.WriteLine(untilSlash("223232-1.jpg"));
Console.WriteLine(untilSlash("443-2.jpg"));
Console.WriteLine(untilSlash("34443553-5.jpg"));
Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
Console.WriteLine(untilSlash(""));
// Throws exception: Console.WriteLine(untilSlash(null));
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
}
}
Btw - changing regex pattern to "^(.*?)(-|$)"
will allow to pick up either until "-"
pattern or if pattern was not found - pick up everything until end of string.
Use a BackgroundWorker. It will allow you to get callbacks on completion and allow you to track progress. You can set the Result value on the event arguments to the resulting value.
public void UseBackgroundWorker()
{
var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += WorkDone;
worker.RunWorkerAsync("input");
}
public void DoWork(object sender, DoWorkEventArgs e)
{
e.Result = e.Argument.Equals("input");
Thread.Sleep(1000);
}
public void WorkDone(object sender, RunWorkerCompletedEventArgs e)
{
var result = (bool) e.Result;
}
The update statement in all versions of SQL looks like:
update table
set col1 = expr1,
col2 = expr2,
. . .
coln = exprn
where some condition
So, the answer is that you separate the assignments using commas and don't repeat the set
statement.
If you are using python2.7 or above you can use the ability of assertRaises to be use as a context manager and do:
with self.assertRaises(TypeError):
self.testListNone[:1]
If you are using python2.6 another way beside the one given until now is to use unittest2 which is a back port of unittest new feature to python2.6, and you can make it work using the code above.
N.B: I'm a big fan of the new feature (SkipTest, test discovery ...) of unittest so I intend to use unittest2 as much as I can. I advise to do the same because there is a lot more than what unittest come with in python2.6 <.
Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"
*Don't write bin at the end
Simply use map function:
var arrOfObj = arrOfObj.map(function(element){
element.active = true;
return element;
}
Map is pretty decent on compatibility: you can be reasonably safe from IE <= 9.
However, if you are 100% sure your users will use ES6 Compatible browser, you can shorten that function with arrow functions, as @Sergey Panfilov has suggested.
Here is the Python Doc for datetime object using dateutil package..
from dateutil.parser import parse
get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj
Use limitTo filter to display a limited number of results in ng-repeat.
<ul class="phones">
<li ng-repeat="phone in phones | limitTo:5">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)
Look under Providing Mock Location Data. You will find the solution for it.
Assuming Bootstrap and Popper libraries were installed using Nuget package manager, for a web application using Visual Studio, in the Master page file (Site.Master), right below where body tag begins, include the reference to popper.min.js by typing:
<script src="Scripts/umd/popper.min.js"></script>
Here is an image to better display the location:
Notice the reference of the popper library to be added should be the one inside umd folder and not the one outside on Scripts folder.
This should fix the problem.
The way I usually organise is
- src
- main
- java
- groovy
- resources
- test
- java
- groovy
- lib
- build
- test
- reports
- classes
- doc
TL;DR: (As of September 2020) Open the Play Console. Select an app. Select Release > Setup >Advanced settings
. On the App Availability
tab, select Unpublish
.
From https://support.google.com/googleplay/android-developer/answer/9859350?hl=en&ref_topic=9872026:
When you unpublish an app, existing users can still use your app and receive app updates. Your app won’t be available for new users to find and download on Google Play.
Prerequisites
- You have accepted the latest Developer Distribution Agreement.
- Your app has no errors that need to be addressed, such as failing to fill in the content rating questionnaire or provide details about your app's target audience and content.
- Managed publishing is not active for the app you want to unpublish.
To unpublish your app:
Open the Play Console. Select an app. Select
Release > Setup > Advanced settings
. On theApp Availability
tab, selectUnpublish
.
Managed publishing
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date d1 = c.getTime(); //the midnight, that's the first second of the day.
should be Fri Mar 09 00:00:00 IST 2012
I tried the following, and none worked:
npm uninstall nodemon
sudo npm uninstall -g nodemon
What did work was:
sudo npm install -g --force nodemon
This kind of logic could be implemented using EXISTS
:
CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');
Query:
DECLARE @a INT;
--SET @a = 1; -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1; -- all values
SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');
It could be extended to contain multiple params:
SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');
You can literally convert it into float using:
float_value = float(integer_value)
Likewise, you can convert an integer back to float datatype with:
integer_value = int(float_value)
Hope it helped. I advice you to read "Build-In Functions of Python" at this link: https://docs.python.org/2/library/functions.html
The most reliable way I have found to do this is to use np.savetxt
with np.loadtxt
and not np.fromfile
which is better suited to binary files written with tofile
. The np.fromfile
and np.tofile
methods write and read binary files whereas np.savetxt
writes a text file.
So, for example:
a = np.array([1, 2, 3, 4])
np.savetxt('test1.txt', a, fmt='%d')
b = np.loadtxt('test1.txt', dtype=int)
a == b
# array([ True, True, True, True], dtype=bool)
Or:
a.tofile('test2.dat')
c = np.fromfile('test2.dat', dtype=int)
c == a
# array([ True, True, True, True], dtype=bool)
I use the former method even if it is slower and creates bigger files (sometimes): the binary format can be platform dependent (for example, the file format depends on the endianness of your system).
There is a platform independent format for NumPy arrays, which can be saved and read with np.save
and np.load
:
np.save('test3.npy', a) # .npy extension is added if not given
d = np.load('test3.npy')
a == d
# array([ True, True, True, True], dtype=bool)
I expanded the Bootstrap table styles as Davide Pastore did, but with that method the styles are applied to all child tables as well, and they don't apply to the footer.
A better solution would be imitating the core Bootstrap table styles, but with your new class:
.table-borderless>thead>tr>th
.table-borderless>thead>tr>td
.table-borderless>tbody>tr>th
.table-borderless>tbody>tr>td
.table-borderless>tfoot>tr>th
.table-borderless>tfoot>tr>td {
border: none;
}
Then when you use <table class='table table-borderless'>
only the specific table with the class will be bordered, not any table in the tree.
You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:
func FillStruct(data map[string]interface{}, result interface{}) {
t := reflect.ValueOf(result).Elem()
for k, v := range data {
val := t.FieldByName(k)
val.Set(reflect.ValueOf(v))
}
}
Working sample: http://play.golang.org/p/PYHz63sbvL
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
Visual Studio 2013 natively supports Git.
See the official announcement.
If you use HashSet
instead of List
for listofGenres
you can do:
var genres = new HashSet<Genre>() { "action", "comedy" };
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));
Inline version:
<a href="http://yoursite.com/" style="text-decoration:none">yoursite</a>
However remember that you should generally separate the content of your website (which is HTML), from the presentation (which is CSS). Therefore you should generally avoid inline styles.
See John's answer to see equivalent answer using CSS.
case when field1>0 then field2/field1 else 0 end as field3
myDummy[myDummy$country == "Austria "] <- "Austria"
After this, you'll need to force R not to recognize "Austria "
as a level. Let's pretend you also have "USA"
and "Spain"
as levels:
myDummy$country = factor(myDummy$country, levels=c("Austria", "USA", "Spain"))
It is a little less intimidating than the highest voted response, but it should still work.
For cmd shell scripting in Windows 7, I use the following fragment in my batch file to find MSBuild.exe in the .NET Framework version 4. I assume version 4 is present, but don't assume the sub-version. This isn't totally general-purpose, but for quick scripts it may be helpful:
set msbuild.exe=
for /D %%D in (%SYSTEMROOT%\Microsoft.NET\Framework\v4*) do set msbuild.exe=%%D\MSBuild.exe
For my uses I'm exiting the batch file with an error if that didn't work:
if not defined msbuild.exe echo error: can't find MSBuild.exe & goto :eof
if not exist "%msbuild.exe%" echo error: %msbuild.exe%: not found & goto :eof
You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:
import re
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring)
return bool(self.rematch)
def group(self,i):
return self.rematch.group(i)
for statement in ("I love Mary",
"Ich liebe Margot",
"Je t'aime Marie",
"Te amo Maria"):
m = REMatcher(statement)
if m.match(r"I love (\w+)"):
print "He loves",m.group(1)
elif m.match(r"Ich liebe (\w+)"):
print "Er liebt",m.group(1)
elif m.match(r"Je t'aime (\w+)"):
print "Il aime",m.group(1)
else:
print "???"
Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:
import re
for statement in ("I love Mary",
"Ich liebe Margot",
"Je t'aime Marie",
"Te amo Maria"):
if m := re.match(r"I love (\w+)", statement):
print("He loves", m.group(1))
elif m := re.match(r"Ich liebe (\w+)", statement):
print("Er liebt", m.group(1))
elif m := re.match(r"Je t'aime (\w+)", statement):
print("Il aime", m.group(1))
else:
print()
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:
final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);
And your dimens.xml will have:
<dimen name="dimen_entry_in_dp">72dp</dimen>
Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.
I'm not sure about the issue for making the top level anchor element a clickable anchor but here's the simplest solution for making desktop views have the hover effect, and mobile views maintaining their click-ability.
// Medium screens and up only
@media only screen and (min-width: $screen-md-min) {
// Enable menu hover for bootstrap
// dropdown menus
.dropdown:hover .dropdown-menu {
display: block;
}
}
This way the mobile menu still behaves as it should, while the desktop menu will expand on hover instead of on a click.
You can use standard STL function distance as mentioned before
index = std::distance(s.begin(), it);
Also, you can access string and some other containers with the c-like interface:
for (i=0;i<string1.length();i++) string1[i];
Try this:
SELECT ProductName,NumberofProducts ,NumberofProductssold
FROM table1
JOIN table2
ON table1.ProductName = table2.ProductName
Your type may reference other assemblies which cannot be found neither in the GAC nor in your local bin folder ==> ...
"or one of its dependencies. The system cannot find the file specified"
Can you give an example of the type you want to serialize?
Note: Ensure that your type implements Serializable.
Check what git remote -v
returns: the account used to push to an http url is usually embedded into the remote url itself.
https://[email protected]/...
If that is the case, put an url which will force Git to ask for the account to use when pushing:
git remote set-url origin https://github.com/<user>/<repo>
Or one to use the Fre1234 account:
git remote set-url origin https://[email protected]/<user>/<repo>
Also check if you installed your Git For Windows with or without a credential helper as in this question.
The OP Fre1234 adds in the comments:
I finally found the solution.
Go to:Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials
Under
Generic Credentials
there are some credentials related to Github,
Click on them and click "Remove
".
That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper
output (it should be manager
)
Use showWarnings = FALSE
:
dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))
dir.create()
does not crash if the directory already exists, it just prints out a warning. So if you can live with seeing warnings, there is no problem with just doing this:
dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))
The **
operator in Python is really "power;" that is, 2**3 = 8
.
i have recently start visual studio code and have this issue and just write the exact path of executable git solve the issue .... here is the code ...
"git.path": "C:\Program Files\Git\bin\git.exe",