text:
Q: Как сделать, чтобы фоновое изображение изменялось в зависимости от устройства? Есть сайт: alicegoes.com - сделан мной с помощью приложения Mobirise, которое использует bootstrap. Прога удобная, результат качественный, но функционал ограничен. Для первой итерации - самое оно, а дальше ручками по мелочи. Например, подцепил гугл-шрифты, заменил плавающий в параллаксе текст на картинку с лого, перенес иконки соц.сетей в шапку сайта из блока в теле и т.п.
На сайте самый верхний блок (сейчас афиша) при просмотре с ПК отображается как надо. Но вот при просмотре со смартфона - отображается только середина фонового изображения, видимо потому что задано заполнение картинкой во всю высоту экрана. Соответственно, это меня не устраивает.
Так оторажается с компа:

Так отображается с телефона (прошу прощения за масштаб, хз как уменьшить):

Вариантов решения проблемы вижу два:
1) с помощью атрибутов media и/или source выбирать какая картинка будет отображается на устройстве в зависимости от его типа
2) перезадать условие заполнения верхнего блока - не по высоте, а по ширине (не смог найти где это задано).
Первый вариант желаннее, но похоже, что без полного перетряхивания кода это не сделать, потому что картинка выбирается в атрибуте background, в который вроде как нельзя указать какой-то выбор (в отличие от picture), а при использовании picture картинка выбирается, но отображение сайта на смартфоне становится некорректным.
Еще есть мысль сделать свой section с параллаксом самому, с нуля... Но я вообще мало чего во всем этом понимаю и по сути могу только "накликать сайт мышкой") Все вышеописанные познания - результат убитых двух дней в гугле.
В общем, пожалуйста, помогите разобраться и реализовать эти идеи, буду очень признателен.
Вот ссылка на архив с сайтом: https://drive.google.com/open?id=18LaaYVzs7eJaS2vbMi21xlZ2FHkhKoGC - если у кого-то найдется время заглянуть в код или даже его поправить - будет просто офигительно!
UPD: решил добавить код

A: Вариант 1:
background-size: 100vw;

или
background-size: 100%;

Картинка будет занимать 100% ширины окна (если она задана как фон div-а)
Вариант 2:
@media(max-width: <число>px){/*задаем размеры картинки*/}

Не забудьте подключить в header
<meta name="viewport" content="width=device-width, initial-scale=1">

A: В общем, всем спасибо за отзывчивость, но решить проблему самостоятельно у меня так и не получилось. В итоге нашел через друзей веб-программиста, который за пять минут все пофиксил удаленно, за что ему огромное спасибо) Не знаю, можно ли здесь указывать контакты хороших людей, поэтому если кому надо - пишите мне, я поделюсь ;)


text:
Q: Can we define the homology of the homology chain complex Let $(C,\partial)$ be a chain complex where each $C_i$ is an $R$-module (R being a given ring). We know that the quotients $H_i(C,\partial)=\ker(\partial_i)/Im(\partial_{i+1}$ are also $R$-modules. I wonder if the family $\{H_i\}_{i\geq 0}$ forms a new chain complex, I mean under what conditions, there exists a family of $R$-module homomorphisms $d_i:H_i(C, \partial)\rightarrow H_{i-1}(C, \partial)$ such that $d_{i}\circ d_{i+1}=0$
Now if such a chain complex $(H(C,\partial),d)$ exists, then we can take its $i$th homology $R$-module:
$H_i(H(C,\partial),d))$, does this "homology of homology" has an algebraic/topological meaning?
What happens if we take a cochain complex instead of a chain complex, is the situation similar?

redpajama_set_name: RedPajamaStackExchange


text:
Q: HIVE Query Deleting source data blob I am using a Azure HdInsight(3.1.3.577).
running the HIVEQL statement:
LOAD DATA INPATH '/myData/employee.txt' INTO TABLE employee;
loads the data correctly but also has the side effect of removing the source text file. This behavior is puzzling to me.
In the documentation (https://cwiki.apache.org/confluence/display/Hive/GettingStarted) there is the following
"loading data from HDFS will result in moving the file/directory. As a result, the operation is almost instantaneous."
My confusion is why this would be efficient, given that the HDFS (Azure blobstore) has to be loaded afresh with the source data for each run.

A: Hive uses HDFS to store it's tables data under default location "/user/hive/warehouse".
When the data is already exists in HDFS, we create a External table and provides the HDFS path using LOCATION keyword. This will not result in moving the file / directory to default location.
By doing this Hive assumes that the data exists in the given path and it doesn't owns the data.
Even if you drop the table, the data specified in the path still exists.

A: try this,
create external table myTable (Userid string, name string)
row format delimited
fields terminated by '\t'
LOCATION '/myData/employee.txt' ;

Location should be in hdfs;


text:
Q: Count number of records returned by group by How do I count the number of records returned by a group by query,
For eg:
select count(*)
from temptable
group by column_1, column_2, column_3, column_4

Gives me,
1
1
2

I need to count the above records to get 1+1+1 = 3.

A: The simplest solution is to use a derived table:
Select Count(*)
From    (
        Select ...
        From TempTable
        Group By column_1, column_2, column_3, column_4
        ) As Z

Another solution is to use a Count Distinct:
Select ...
    , ( Select Count( Distinct column_1, column_2, column_3, column_4 )
        From TempTable ) As CountOfItems
From TempTable
Group By column_1, column_2, column_3, column_4

A: How about:
SELECT count(column_1)
FROM
    (SELECT * FROM temptable
    GROUP BY column_1, column_2, column_3, column_4) AS Records

A: A CTE worked for me:
with cte as (
  select 1 col1
  from temptable
  group by column_1
)

select COUNT(col1)
from cte;

A: In PostgreSQL this works for me:
select count(count.counts)
from
    (select count(*) as counts
     from table
     group by concept) as count;

A: I know it's rather late, but nobody's suggested this:
select count ( distinct column_1, column_2, column_3, column_4)
from   temptable

This works in Oracle at least - I don't currently have other databases to test it out on, and I'm not so familiar with T-Sql and MySQL syntax.
Also, I'm not entirely sure whether it's more efficient in the parser to do it this way, or whether everyone else's solution of nesting the select statement is better.  But I find this one to be more elegant from a coding perspective.

A: You can do both in one query using the OVER clause on another COUNT
select
    count(*) RecordsPerGroup,
    COUNT(*) OVER () AS TotalRecords
from temptable
group by column_1, column_2, column_3, column_4

A: Try this query:
select top 1 TotalRows = count(*) over ()
from yourTable
group by column1, column2

A: I was trying to achieve the same without subquery and was able to get the required result as below
SELECT DISTINCT COUNT(*) OVER () AS TotalRecords
FROM temptable
GROUP BY column_1, column_2, column_3, column_4

A: You could do:
select sum(counts) total_records from (
    select count(*) as counts
    from temptable
    group by column_1, column_2, column_3, column_4
) as tmp

A: Can you execute the following code below. It worked in Oracle.
SELECT COUNT(COUNT(*))
FROM temptable
GROUP BY column_1, column_2, column_3, column_4

A: you can also get by the below query
select column_group_by,count(*) as Coulm_name_to_be_displayed from Table group by Column;

-- For example:
select city,count(*) AS Count from people group by city

A: Here what i did
SELECT COUNT(OwnerID) FROM (SELECT OwnerID FROM #resultsTable GROUP BY OwnerID) AS c

A: How about using a COUNT OVER (PARTITION BY {column to group by}) partitioning function in SQL Server?
For example, if you want to group product sales by ItemID and you want a count of each distinct ItemID, simply use:
SELECT
{columns you want} ,
COUNT(ItemID) OVER (PARTITION BY ItemID) as BandedItemCount ,
{more columns you want}... ,
FROM {MyTable}

If you use this approach, you can leave the GROUP BY out of the picture -- assuming you want to return the entire list (as you might do report banding where you need to know the entire count of items you are going to band without having to display the entire set of data, i.e. Reporting Services).

A: Following for PrestoDb, where FirstField can have multiple values:
select *
            , concat(cast(cast((ThirdTable.Total_Records_in_Group * 100 / ThirdTable.Total_Records_in_baseTable) as DECIMAL(5,2)) as varchar), '%') PERCENTage
from
(
    SELECT FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable, count(*) Total_Records_in_Group
    FROM BaseTable FirstTable
    JOIN (
            SELECT FK1, count(*) AS Total_Records_in_baseTable
            FROM BaseTable
            GROUP BY FK1
        ) SecondTable
    ON FirstTable.FirstField = SecondTable.FK1
    GROUP BY FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable
    ORDER BY FirstTable.FirstField, FirstTable.SecondField
) ThirdTable


text:
Q: Route alias, is it possible? I have a Vehicle model:
Routes:
map.resources :vehicles, :has_many => :suppliers

Everything works great, but Vehicle has a boolean attribute is_truck. I want to make an Alias so I can get the same resources filtering only trucks, I tried with:
Routes:
map.trucks '/trucks', :controller => :vehicles, :action => :index, :is_truck => true
map.trucks '/trucks/by_supplier/:supplier', :controller => :vehicles, :action => :index, :is_truck => true

The first one works well, but when I search within a Form the second doesn't work and searches all suppliers.
Controller:
class VehiclesController
   def index
     if params[:supplier]
       @vehicles = Vehicle.all :conditions => { :is_truck => params[:is_truck] }
     else
       @vehicles = Vehicle.all
     end
   end
   ...
end

Search Form:
<% form_for :truck, :url => {:controller => :trucks, :action => :index}, :html => {:method => :get} do |f| %>
  <% f.text_field :search %>
  <% f.submit 'Search Trucks' %>
<% end %>

Is it possible to map.resources as an alias ?

A: I found a cleaner way to do it, but Search is still broken under a specific supplier:
# Show all vehicles
map.connect '/vehicles/supplier/:supplier', :controller => :vehicles, :action => :index
map.resources :vehicles

# Only show trucks
map.connect '/trucks/supplier/:supplier', :controller => :vehicles, :action => :index, :is_truck => true
map.resources :vehicles, :as => 'trucks', :requirements => { :is_truck => true }

Resource: http://api.rubyonrails.org/classes/ActionController/Resources.html

A: Just amend your routes in the following way:
map.resources :vehicles, :has_many => :suppliers,
                         :collection => { :trucks => :get }

And check rake routes for the routes this generates. It will allow you to list vehicles which are trucks:
trucks_vehicles GET /vehicles/trucks(.:format)
                    {:controller=>"vehicles", :action=>"trucks"}

So you now just need to add a new action called "trucks" which works similar to "index". Forms should keep track on it's own (via form fields) if you create a truck or another vehicle. Don't try to trick around with rails routing, which usually would mean your app design is flawed which will get you into trouble later.
You may take a look at STI (single table inheritance: one table stores multiple classes of vehicles). Another way would be to create a trucks controller which inherits from the vehicles controllers and overwrites just some methods like so:
class TrucksController < VehiclesController
  def new
    @is_truck = true
    super
  end
  ...
end

or
class TrucksController < VehiclesController
  before_filter :this_is_a_truck
  ...

  private

  def this_is_a_truck
    @is_truck = true
    super
  end
end

Update: Here's another one (given you have a is_truck column):
class TrucksController < VehiclesController
  around_filter :with_truck_scope
  ...

  private

  # Scope every active record access with an is_truck condition
  # you may want to put this directly into the model to get rid of the .send
  # method and directly access "Vehicle.with_truck_scope &block" here
  def with_truck_scope(&block)
    Vehicle.send :with_scope, :find => { :conditions => "is_truck = 1" },
                              :create => { :is_truck => 1 }, &block
  end
end

But I recommend really first to try out going with the :collection and :member parameters of Rails' routing.

A: are you processing it in your controller?
smth like:
class VehiclesController
   def index
     if params[:supplier]
       @vehicles = Vehicle.all :conditions => { :supplier_id => params[:supplier] }
     else
       @vehicles = Vehicle.all
     end
   end
end

A: Not sure if it's possible to make an alias but at least you can try to swap your routes:
map.trucks '/trucks/by_supplier/:supplier', :controller => :vehicles, :action => :index, :is_truck => true
map.trucks '/trucks', :controller => :vehicles, :action => :index, :is_truck => true

Since routes works like 'first added - has higher priority' your solution could fail since map.trucks '/trucks' catch '/trucks/by_supplier/:supplier' as well. Also I'd recommed to refactor it a bit:
map.with_options :controller => :vehicles, :action => :index, :is_truck => true do |v|
  v.trucks '/trucks/by_supplier/:supplier'
  v.trucks '/trucks'
end

A: I recommend you to use another resource, just adding:
map.resources :vehicles, :as => :trucks, :has_many => :suppliers

Then handle it in your controller with something like:
def index
  conds = {}
  conds = { ... } if request.uri =~ /trucks/ # you can be more specific about the regexp if you need to
  @vehicles = Vehicle.all :conditions => conds
end

What do you think about it?


text:
Q: Upgrade Ubuntu Kernel auto/manual I've upgraded my ubuntu server kernel to 5.12 manually because of the Intel UHD 750 driver. My question is, will "apt dist-upgrade" upgrade that kernel once the official/signed one is above 5.12, or as I've installed it manually, automatic upgrades are disabled now?
I'm running Ubuntu 20.04 LTS.
This is what I did:
I've downloaded from the ubuntu mainline web the following packages and I've installed them:

*

*linux-headers-5.12.4-051204_5.12.4-051204.202105140931_all.deb

*linux-headers-5.12.4-051204-generic_5.12.4-051204.202105140931_amd64.deb

*linux-image-unsigned-5.12.4-051204-generic_5.12.4-051204.202105140931_amd64.deb

*linux-modules-5.12.4-051204-generic_5.12.4-051204.202105140931_amd64.deb

The reason is: After Kernel 5.11, there is support for new Intel UHD 750 Integrated Graphic Cards. The oficial kernel has not support, but once the official kernel goes above 5.12, I want to keep upgrading the kernel in the "regular" way (dist-upgrade).
Thanks in advance!

A: Will "apt dist-upgrade" upgrade that kernel once the official/signed one is above 5.12?
Let's make two assumptions:

*

*Your kernel metapackage (linux-image-generic) is still installed

*Your 5.12 kernel, if provided by a deb package, does not match the normal Ubuntu kernel naming schema.

If these assumptions are true, then your 5.12 kernel is independent of any Ubuntu kernel metapackage. Apt will continue to download new (lower-version) kernels as directed by the kernel metapackage, and those will exist side-by-side with your 5.12 kernel.
Eventually, the kernel version on the Ubuntu-provided path will pass 5.12. Your existing 5.12 won't be replaced by Ubuntu-provided packages because the names don't match. You will have two 5.12 kernels side-by-side.
When the Ubuntu-provided kernel bumps again to (let's say, 5.14 for example), the Ubuntu-provided 5.12 will be automatically removed. Your manually-provided 5.12 must be manually removed.

If the kernel metapackage assumption is false, then the answer is simple: You won't get any more Ubuntu-provided kernels.
If the naming schema assumption is false, then you will get apt errors when the real Ubuntu 5.12 kernel package does not match your 5.12 kernel package.


text:
Q: How to request for a non-json octet-stream in angular 6 using HttpClient? I am working on an Angular 6 project. One of the web service return the octet-stream of a file. I have to create a Blob of the file and download it. I am not getting the response inside subscribe. How can I request for non-json octet-stream response?
downloadFile(filePath: string): Observable<HttpResponse<Any>> {
    this.http.post<any>(this.getFileDownloadPath(), { stringParam: filePath }, { observe: 'response' }).subscribe(
        (resp) => {
            this.triggerDownloadFile(resp.body);
        },
        (err) => {
            console.log('err');
        }
    );
}

triggerDownloadFile(data: Response) {
    const blob = new Blob([data], { type: 'application/octet-stream' });
    const url = window.URL.createObjectURL(blob);
    window.URL.revokeObjectURL(url);
    window.open(url);
}

A:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular 5';
  fileUrl;
  constructor(private sanitizer: DomSanitizer) {  }
  ngOnInit() {
    const data = 'some text';
    const blob = new Blob([data], { type: 'application/octet-stream' });

    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
  }

}
<a [href]="fileUrl" download="file.txt">DownloadFile</a>


text:
Q: Stack overflow IE8 error I have problem with p:calendar(Primefaices tag for date) and IE8. When i click on the input text, the IE window freezes and then launches 'Stack overflow in line 16' error. I checkout out the Javascript debug in IE8, it seems that an infinite call was launched. The problem does not occur with FireFox, and  Chrome.
Here the code
<p:calendar value="#{calendarBean.date2}" id="popupCal" />

Thanks for help!


text:
Q: Customising UITabBarItems in their controllers? In previous applications I have customised my tabBarItems by overriding init (see below)
- (id)init {
    self = [super init];
    if(self) {
        UITabBarItem *tabBarItem = [self tabBarItem];
        [tabBarItem setTitle:@"ONE"];
    }
    return self;
}

After looking at the Xcode templates I am now thinking that I would be better to add this customisation to initWithNibName:bundle: instead.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        UITabBarItem *tabBarItem = [self tabBarItem];
        [tabBarItem setTitle:@"ONE"];
    }
    return self;
}

does this make sense, it seems like it does to me, but I just wanted to check?
Gary

A: It depends on whether you load your controller from a Nib (xib) file or not (and so you do all the work programmatically in the init) I guess


text:
Q: live tv stream to ipad 1 or 2 using vlc command line and html5 from analog TV card on ubuntu linux My system:
I run ubuntu natty, and have an old analog TV card, the winTV-go +FM. and vlc 1.1.9., apache2
What I want to achieve:
take the output of my old tv card, stream it with vlc and have the stream embedded on a local site to be displayed with html5, so i can watch the stream on my ipad 1 or 2
Current situation:
I have managed to get streaming with vlc working (i don't use the gui) with different containters and codecs. I have 3 working stream-commands that include:
1: vlc -vvv v4l2:///dev/video0:width=640:height=480 :input-slave=alsa://hw:1,1 --sout '#transcode{vcodec=mp4v,acodec=mp3,vb=8000,ab=128,channels=1,samplerate=44100}:standard{access=http,mux=ts,dst=192.168.1.10:9090}'

2: vlc -vvv v4l2:///dev/video0:width=640:height=480 :input-slave=alsa://hw:1,1 --sout '#transcode{vcodec=theo,acodec=mp3,vb=8000,ab=128,channels=1,samplerate=44100}:standard{access=http,mux=ogg,dst=192.168.1.10:9080/test.ogv}'

3: vlc -v v4l2:///dev/video0:width=640:height=480 :input-slave=alsa://hw:1,1 --sout '#transcode{vcodec=h264,vb=1024,acodec=mp3,channels=1,ab=128,samplerate=44100}:standard{access=http,mux=ts,dst=192.168.1.10:9080/test.mp4}'

I can open all 3 streams on a different computer and play them in vlc, Note on the side: the *.ogv stream i can also just enter as an url (http://192.168.1.10:9080/test.ogv) in chrome and it displays it there as a video, the other 2 streams it tries to download as a file.
So far so good, now I come to my html5 code (had some trouble pasting it here, so i used pastebin to dsiplay the code):
pastebin html5 code
this works perfectly in chrome, but because it is ogv it will of course not work on the ipad, so i need to use h.264/mp4 as that is supported/built in with safari, but when using the stream command 1 or 3 then i get no video displayed on ipad or chrome.
When not using stream-command 2 (the ogv command) I adjust the html5 code to one of the following (I have tried all 3):
  <source src=http://192.168.1.10:9080/test.mp4 type=video/mp4; codecs="avc1.4D401E, mp3"'>

or
 <source src=http://192.168.1.10:9080/test.mp4 type=video/mp4'>

or
 <source src=http://192.168.1.10:9080/test.mp4'>

none of these work.
I have also added mime types to my /etc/mime.types
video/mp4                                       mp4
video/quicktime                                 qt mov
video/mp4v-es
video/ogg                                       ogv
video/webm                                      webm
video/x-matroska                                mpv mkv
application/x-mpegURL                           m3u8
video/MP2T                                      ts
application/x-mpegURL .m3u8
how do I have to specify the html5 code for it to be properly displayed on my ipad? anyone got a clue?
btw I have also tried http apple live stream using ffmpeg and segmenter and i get that working as well, but due to the fact that TV is a continuous stream of data it does not work well with the playlist, so i stops after a while and you need to restart etc, not very handy and i want the above working, would appreciate the help, thanks in advance :)

A: For HTML5 and h.264 you have to use AAC as the audio codec and mp4 as the mux, where you are currently using mp3 for audio and TS for mux. That said, I don't have VLC live streaming via HTML5 video working yet.
iPad viewers of my live web show are watching via the oPlayer free app on my h.264/AAC/FLV stream that I also use for Flash clients, but I'm hoping to get HTML5 live streaming to work.


text:
Q: Java ini4j - reading multiple options from .ini file I'm trying to read multiple values using ini4j, the docs say it should be possible with the Options class.
Here is my sample .ini file (./dwarfs.ini)
[dopey]
age = 23
fortuneNumber = 11
fortuneNumber = 33
fortuneNumber = 55

here is the code to read it:
Ini ini = new Ini();
Config conf = new Config();
conf.setMultiOption(true);
ini.setConfig(conf);
ini.load(new FileReader("./dwarfs.ini"));

but fortuneNumber property is just 55 after reading and I'd want it to be an array or a list, anything.

A: The web presence for the ini4j project contains (among others) very simple tutorials. One of these tutorials explains, how to retrieve multiple values. How could you expect to get a list or an array, when using a fetch method that returns a single reference? Look at the API!
In the tutorial, there is a part explaining multi values:

[ini4j] library introduces MultiMap interface, which is extends normal
  Map, but allows multiply values per keys. You can simply index values
  for a given key, similar to indexed properties in JavaBeans api.

There is also an example:
String n1 = sneezy.get("fortuneNumber", 0);  // = 11
String n2 = sneezy.get("fortuneNumber", 1);  // = 22
String n3 = sneezy.get("fortuneNumber", 2);  // = 33
String n4 = sneezy.get("fortuneNumber", 3);  // = 44

In this example, sneezy is a Section, but it should also work with an Ini.
And just to make it complete: An Ini also knows a method List<V> getAll(Object key).

A: to handle mutliple properties in section use following code :
Ini oINI = new Wini();
Config conf = new Config();
conf.setMultiOption(true);
oINI.setConfig(conf);
oINI.load(new File("....../myfile.ini"));

Do not directly open the INI file in the class creation, set options before, otherwise the options won't be used and by default MultiOption si set to "false".
Have searched a while for this solution.

A: *

*you need setConfig first, and then load file.

*you need use List to handle multiple same values.

here the example:
Ini ini = new Wini();

Config config = new Config();
config.setMultiOption(true);
config.setMultiSection(true);

ini.setConfig(config);   //set config

ini.load(new File(filename));      // load AFTER setConfig

for (String sectionName : ini.keySet()) {
    List<Section> sectionList = ini.getAll(sectionName);  // use List
    for (Section section : sectionList) {
        for (String optionName : section.keySet()) {
            List<String> optionList = section.getAll(optionName);
            for (String optionVaule : optionList) {
                System.out.printf("%s %s %s\n", sectionName, optionName, optionVaule);
            }
        }
    }
}

here the out put:
dopey age 23
dopey fortuneNumber 11
dopey fortuneNumber 33
dopey fortuneNumber 55


text:
Q: How to paste passwords to terminal for use with SSH? Hi I am trying to complete the overthewire challenges. They require you to extract passwords and login as different users to proceed. Passwords are quite lengthy and I am not able to paste the in in terminal for what I believe is OS X design. I have tried circumventing that using sshpass and putty's plink, but to no success. What way can I do that?

A: On macOS when terminal prompts a password it does not show entered characters but it accepts them when you enter. After you paste it with Command (⌘) + V just hit Enter (⏎).

A: The process below works all the time for me, This requires your mouse. Handy for long strings & passwords.

*

*Copy text/string using mouse

*In terminal, using the mouse, position to location and right click to paste

*Terminal will show pasted text.
NOTE: Terminal will not display the pasted string(password), Regardless, hit enter and it should work.


text:
Q: How to get text field values from Dynamically added jquery row? I am having some problem to retrieve input values from dynamically added jquery table row ...
these are my code .. expecting a good solution .. thanks in advance :)

// finaly i need pass the values from text feild ...

<form name="add_row" method="post" action="process.php">

   Name

  <input type="text" name="name"  />

  <g:textField name="company" class="company">

  </g:textField>
      Position

     <input type="text" name="name"  />
  <g:textField name="position" ></g:textField>

<input type="button" class="deleteThisRow"  value="Delete"/>

<input type="button" id="btnAddMore"  value="add more"/>

A: change the text field names to name1,name2,name3....namen
on the php side get the length of array like.
$numoftxtfield = count($_POST);

this gives the length of text field then using for loop or foreach loop get the all values of the text fields.

A: IF you do not want to change name of text field then you can use name as an array like..
     name =  "name[]"
after submit form you can retrive it by implode/explode.


text:
Q: Mysql data manipulation query not return results? I created this query to get data from multiple tables,
DROP TABLE IF EXISTS tmp_acc;
DROP TABLE IF EXISTS tmp_loan;

CREATE
TEMPORARY TABLE
IF NOT EXISTS
tmp_acc AS
    (SELECT
        ac.date,
        COALESCE((SELECT SUM(cash) FROM accounts WHERE MONTH(date) = MONTH(ac.date - INTERVAL 1 MONTH) AND YEAR(date) = YEAR(ac.date - INTERVAL 1 YEAR)), 0)AS op_cash,
        COALESCE((SELECT SUM(bank) FROM accounts WHERE MONTH(date) = MONTH(ac.date - INTERVAL 1 MONTH) AND YEAR(date) = YEAR(ac.date - INTERVAL 1 YEAR)),0)AS op_bank,
        COALESCE((SELECT SUM(ho_funds) FROM accounts WHERE date = ac.date), 0)AS ho_funds,
        COALESCE((SELECT SUM(recieved) FROM funds WHERE date = ac.date AND branch_to = 'kandy' AND method = 'Cash'),0)AS funds_cash,
        COALESCE((SELECT SUM(recieved) FROM funds WHERE date = ac.date AND branch_to = 'kandy' AND method = 'Bank'),0)AS funds_bank,
        COALESCE((SELECT SUM(diposit) FROM bank WHERE date = ac.date),0)AS diposits,
        COALESCE((SELECT SUM(withdraw) FROM bank WHERE date = ac.date ),0)AS withdrawals
    FROM accounts ac);

CREATE
TEMPORARY TABLE
IF NOT EXISTS
tmp_loan AS
    SELECT ls.date, COUNT(l.idloan)AS count, l.interest,l.admission_fee,l.document_fee,l.insuarance,
        (SELECT SUM(d1.overdue) FROM daily_collections d1 WHERE d1.loan_idloan = l.idloan)AS overdue_collection,
        ls.completed_date
    FROM loan l
    LEFT OUTER JOIN daily_collections d ON l.idloan = d.loan_idloan
    JOIN loan_session ls ON ls.loan_idloan = l.idloan
    WHERE ls.completed = 'Yes'
    GROUP BY  ls.completed_date,l.interest;

    SELECT
        a.date,COALESCE(a.op_cash,0)AS op_cash,COALESCE(a.op_bank,0)AS op_bank, COALESCE(a.ho_funds,0)AS ho_funds,
        COALESCE(a.funds_cash,0)AS funds_cash, COALESCE(a.funds_bank,0)AS funds_bank,COALESCE( a.diposits,0)AS diposits, COALESCE(a.withdrawals,0)AS withdrawals,
        COALESCE(l.count,0)AS count, COALESCE(l.interest,0)AS interest, COALESCE(l.admission_fee,0)AS admision_fee,
        COALESCE(l.document_fee,0)AS document_fee, COALESCE(l.insuarance,0)AS insrance, COALESCE(l.overdue_collection,0)AS overdue_collection
    FROM tmp_acc a
    LEFT OUTER JOIN tmp_loan l ON a.date = l.completed_date
    WHERE MONTH(a.date) = MONTH(current_date())

I used this query to generate Jasper report and to view data in java. This query working fine in workbench, and it returns all results.
But it's not working in java. I used Statement.executeQuery() and assign to ResultSet. I printed ResultSet, but nothing is printing.
How can I execute this query in java?
Java code
public ArrayList<cashObject> getCashbookData(String date) {
        ArrayList<cashObject> results = new ArrayList<>();
        try {
            conn c = new conn();
            String query = "DROP TABLE IF EXISTS tmp_acc;\n"
                    + "DROP TABLE IF EXISTS tmp_loan;\n"
                    + "                \n"
                    + " CREATE \n"
                    + "    TEMPORARY TABLE \n"
                    + "    IF NOT EXISTS \n"
                    + "                tmp_acc AS \n"
                    + "                (SELECT\n"
                    + "                ac.date,\n"
                    + "             COALESCE((SELECT SUM(cash) FROM accounts WHERE MONTH(date) = MONTH(ac.date - INTERVAL 1 MONTH) AND YEAR(date) = YEAR(ac.date - INTERVAL 1 YEAR)), 0)AS op_cash,\n"
                    + "                COALESCE((SELECT SUM(bank) FROM accounts WHERE MONTH(date) = MONTH(ac.date - INTERVAL 1 MONTH) AND YEAR(date) = YEAR(ac.date - INTERVAL 1 YEAR)),0)AS op_bank,\n"
                    + "                COALESCE((SELECT SUM(ho_funds) FROM accounts WHERE date = ac.date), 0)AS ho_funds,\n"
                    + "                COALESCE((SELECT SUM(recieved) FROM funds WHERE date = ac.date AND branch_to = 'kandy' AND method = 'Cash'),0)AS funds_cash,\n"
                    + "                COALESCE((SELECT SUM(recieved) FROM funds WHERE date = ac.date AND branch_to = 'kandy' AND method = 'Bank'),0)AS funds_bank,\n"
                    + "                COALESCE((SELECT SUM(diposit) FROM bank WHERE date = ac.date),0)AS diposits,\n"
                    + "                COALESCE((SELECT SUM(withdraw) FROM bank WHERE date = ac.date ),0)AS withdrawals\n"
                    + "                FROM accounts ac);\n"
                    + "                \n"
                    + "                CREATE \n"
                    + "                TEMPORARY TABLE \n"
                    + "                IF NOT EXISTS \n"
                    + "                tmp_loan AS \n"
                    + "                SELECT ls.date, COUNT(l.idloan)AS count, l.interest,l.admission_fee,l.document_fee,l.insuarance,\n"
                    + "                \n"
                    + "                (SELECT SUM(d1.overdue) FROM daily_collections d1 WHERE d1.loan_idloan = l.idloan)AS overdue_collection,\n"
                    + "                ls.completed_date\n"
                    + "                FROM loan l \n"
                    + "                LEFT OUTER JOIN daily_collections d ON l.idloan = d.loan_idloan \n"
                    + "                JOIN loan_session ls ON ls.loan_idloan = l.idloan\n"
                    + "                WHERE ls.completed = 'Yes'\n"
                    + "                GROUP BY  ls.completed_date,l.interest;\n"
                    + "                \n"
                    + "                SELECT\n"
                    + "                a.date,COALESCE(a.op_cash,0)AS op_cash,COALESCE(a.op_bank,0)AS op_bank, COALESCE(a.ho_funds,0)AS ho_funds,\n"
                    + "                COALESCE(a.funds_cash,0)AS funds_cash, COALESCE(a.funds_bank,0)AS funds_bank,COALESCE( a.diposits,0)AS diposits, COALESCE(a.withdrawals,0)AS withdrawals,\n"
                    + "                COALESCE(l.count,0)AS count, COALESCE(l.interest,0)AS interest, COALESCE(l.admission_fee,0)AS admision_fee,\n"
                    + "                COALESCE(l.document_fee,0)AS document_fee, COALESCE(l.insuarance,0)AS insrance, COALESCE(l.overdue_collection,0)AS overdue_collection\n"
                    + "                FROM tmp_acc a \n"
                    + "                LEFT OUTER JOIN tmp_loan l ON a.date = l.completed_date\n"
                    + "                WHERE MONTH(a.date) = '" + date + "' ";

            Statement st = c.getConnection().createStatement();
            ResultSet rs =st.executeQuery(query);

            System.out.println("RS :: " + rs);

            while (rs.next()) {

                cashObject o = new cashObject();
                o.setDate(rs.getString(0));
                o.setOp_cash(parseDouble(rs.getString(1)));
                o.setOp_bank(parseDouble(rs.getString(2)));
                o.setHo_funds(parseDouble(rs.getString(3)));
                o.setFunds_cash(parseDouble(rs.getString(4)));
                o.setFunds_bank(parseDouble(rs.getString(5)));
                o.setDiposits(parseDouble(rs.getString(6)));
                o.setWithdrawals(parseDouble(rs.getString(7)));
                o.setCount(parseInt(rs.getString(8)));
                o.setInterest(parseDouble(rs.getString(9)));
                o.setAdmission_fee(parseDouble(rs.getString(10)));
                o.setDocument_fee(parseDouble(rs.getString(11)));
                o.setInsuarance(parseDouble(rs.getString(12)));
                o.setOverdueCollection(parseDouble(rs.getString(13)));
                results.add(o);
            }
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
        // print size of arraylist
        System.out.println("CLASS : " + results.size());
        return results;
    }

A: With default configuration, you can't execute multiple statements like that, because a statement is intended to execute a single statement, not a script.
You need to execute the five statements in your script separately, so
statement.execute("drop table ...");
statement.execute("drop table ...");
statement.execute("create temporary table ...");
statement.execute("create temporary table ...");
ResultSet rs = statement.executeQuery("select ...");

Alternatively, you could try to use the MySQL specific connection property allowMultiQueries=true; this will allow you to execute multiple statements. Its behavior is technically not allowed by the JDBC standard, and I don't know if it will work or not for this specific example.


text:
Q: How to add coins fast as fractions When you have a problem that requires you to add coins together. Is it better to use fractions?
For example, you have 14 one dollar bills, 24 quarters, 12 dimes, 78 nickles, and 20 pennies.
So I know that I can just take:
$$\begin{align*}
14 \times 1 &= \$14\\
24 \times .25 &= \$6\\
12 \times .10 &= \$1.20\\
78 \times .05 &= \$3.90\\
20 \times .01 &= \$0.20
\end{align*}$$
Easy stuff, but I'm trying to figure out the best way to add these up. Assuming I have only 15-30 seconds to get this addition done without calculator. I figured the best way is to use fractions.
ps. Can someone tell me how to write real fractions in here instead of using slash? I just want to write them to look better in the future, I tried to look for a way in FAQ but didn't see anything on formatting.
Thanks

A: I would try to "simplify" the problem a little. For instance, you know 4 quarters is a dollar, so 24 / 4 is 6 dollars. 10 dimes to a dollar, so you have 1 dollar and twenty cents. 20 nickels to a dollar, so you have 3 dollars (60 nickels), and 18 nickels left over.
So now we're at 14 + 6 + 1 + 3 = 24 dollars (and don't forget the remaining 2 dimes, 18 nickels, and 20 pennies).
Simplifying the problem like this might make it easier - at least, that's how I would do it in my head.


text:
Q: The Resolving Power of a spectrometer I can't understand one thing in the definition of the resolving power of a spectrometer:
Let the resolving power be defined as: $R=\frac{\lambda}{\Delta \lambda}$ where $\Delta \lambda$ is the separation of two resolved spectral lines and $\lambda$ is the average wavelength of the two lines.
I understand that if $\Delta \lambda$ is smaller then $R$ must be greater, because if the spectrometer can resolve two close spectral lines then its resolving power is greater but why do we need that $\lambda$ in the numerator?
If we have two lines with the same $\Delta \lambda$ but with smaller r wavelengths, why is the resolving power higher?
From my point of view I would simply define it as: $R=\frac{1}{\Delta \lambda}$, so why that numerator?

A: Because resolving power is unitless. By definition.
You can define something called the "resolution" of a spectrometer, which is just $\Delta \lambda$, which has units.
Why is a unitless resolving power useful? One reason is that it arises naturally in the properties of a simple diffraction grating, where the resolving power is just the order multiplied by the number of rule lines on the grating, and is independent of wavelength.
A further reason, especially in astronomy, is that it can be directly translated into a velocity resolution that is independent of wavelength $\Delta v = c/R$.

A: $\dfrac{\Delta \lambda}{\lambda}$ is the fractional change which can be resolved and the reciprocal is the resolving power which has no units.
So in terms of a fractional change $\dfrac{1\,\rm nm}{400\,\rm nm}$ is the same as $\dfrac{2\,\rm nm}{800\,\rm nm}$ ie you can say that the resolving power in terms of a fractional change is the same.
However that equivalence of resolution is not as obvious if you just compare $(1/)\Delta \lambda$ ie $(1/)1\,\rm nm$ vs $(1/)2\,\rm nm$ and note that a unit would need to be included.


text:
Q: No such module 'Alamofire' when i try Archive app When i run the app i haven´t any problem.
But when i try archive for deploy app i have this error "No such module 'Alamofire'" in specific class.
I tried clean and build project, and i don´t have any problem.
My pod file like this
platform :ios '9.0'
use_frameworks!
target 'app_name' do
   pod 'Alamofire', '~> 4.0'
   pod 'PayPal-iOS-SDK', '~> 2.12.0'
   pod 'moa', '~> 8.0'
   pod 'Auk', '~> 7.0'
   pod 'AZSClient'
end

What might be happening?

A: Clear your DerivedData then clean and build your project.
To clear Derived Data:

*

*Goto xcode preferences or press ⌘,

*Then select Locations option

*Click on the arrow showing near the DerivedData path, it will open DerivedData folder.

*Select all folders and files (⌘A) inside the DerivedData folder and delete(⌘Del).


text:
Q: jQuery slide up/down: not effect content below it? So I have a div that is displayed by default. I'm using a function to slideUp the element, then change the content, then slideDown back to reveal the new info.
And that's all working fine.
What's bothering me is that when the div is animating everything below it follows it up and down.
Basically, it seems like as it's hiding it's "display: none" -ing so to speak, meaning it's being taken out of the flow.
And I want it to be more like "visibility: hidden".
...if that makes sense (God, I hope it does. It has been a long week. =P)

A: Elements slide up to fill gaps when above elements are removed. For HTML, gravity is upward, which is why we build HTML downward(from the top of the browser, down).
Let's pretend your object sliding upward is as follows:

Hello!

What you need to do is wrap that div in another div that holds the same height:

Hello!

This way, when the first element crushes, the gap will be held open by the parent div.

A: I think the easiest thing to do would be to put the Slide element inside a div with a fixed height. For example

Then set then set set the slider jquery, I am assuming you have this done already and don't need to see it.
The CSS would look like:
div.wrapper {height: 250px; overflow: hidden;}
div.slider {max-height: 250px;}

This way, the slider moves up and down inside a fixed size element and the rest of the elements will be unaffected.


text:
Q: python bindings for android adb i'm creating an automation framework in python for our android devices.
i've written a wrapper for adb commands by using Popen to run adb.
this is nice but i'de rather skip on the process creating for every call (many calls to adb)
So i thought about creating bindings for the C code (adb is in C).
As far as i understand there are 3 options:
1. compile adb as an SO and use ctypes.
2. create python extension using python.h and add adb source code to the compilation making a full python interface to the command.
3. doing the same like #2 using Cython.
Since i've never done it before, any recommendation for which method is better for my scenario ? consider performance and time to market.

A: No need for c bindings. Just use sockets to connect to the adb daemon from your python code https://gist.github.com/ktnr74/6755712


text:
Q: Setting the content size of my UIScrollView in viewDidLoad/viewWillAppear has no effect - why? I'm trying to force the content size of my UIScrollVIew when it's container loads. I'm finding this much more difficult than I'd imagine it would be. I've tried setting the content size in both viewDidLoad and viewWillAppear, like so:
-(void)viewWillAppear:(BOOL)animated
{
    CGSize newContentSize = CGSizeMake(scrollView.contentSize.width, scrollView.frame.size.height + 80.0);
    [scrollView setContentSize:newContentSize];
}

If I place a breakpoint right after I call setContentSize, I can see that the new content size is indeed what I set it to.
However, if I then check the content size at some arbitrary point after viewWillAppear, such as, say, scrollViewDidScroll, the content size has reverted back to the size of the "actual" content in the scroll view, and not the size I tried forcing it to be in viewDidAppear.
Why is this?

A: I have no idea what is resetting it on you, but I can help you find the answer.
What I usually do in a situation like this is subclass UIScrollView (usually as "XXXUIScrollView"), override setContentSize: (to just call [super setContentSize:size], maybe with an NSLog), and set a breakpoint in the overridden method to see what is setting the value.

A: I got exactly the same problem and the only workaround I found so far was to do performSelector:withObject:afterDelay - to set the contentSize property after some small delay:
UIScrollView won't scroll even when I set content size


text:
Q: RazorPDF save pdf file to server directory in MVC4 I am currently assembling and displaying a PDF using RazorPDF in MVC4 and would like to save the PDF file to the file system at the same time I return the view.
The following line of code in the controller action is calling the view:
return new PdfResult(claims, "PDF");

A: I was able to finally write the pdf to the directory system by changing the code base of the RazorPDF render method. The Rendor method creates a PdfWriter object that is associated to the response stream:
        // Associate output with response stream
        var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream);
        pdfWriter.CloseStream = false;

The solution was to create another PdfWriter object that was associated to a FileStream object  as illustrated below:
        // Create the pdf file in the directory system
        var fileStream = new FileStream(myPdfFilePath, FileMode.Create);
        var pdfWriter2 = PdfWriter.GetInstance(document, fileStream);

I then closed the objects:
        fileStream.Close();

        pdfWriter.Close();
        pdfWriter2.Close();

I had to essentially incorporate the PdfResult and PdfView classes of RazorPDF into my own project and significantly alter the code. The reason is because I also had to encorporate calls to an email class that sent the pdf to a user.
The full Render method is displayed below:
    public void Render(ViewContext viewContext, TextWriter writer)
    {
        // generate view into string
        var sb = new System.Text.StringBuilder();
        TextWriter tw = new System.IO.StringWriter(sb);
        myResult.View.Render(viewContext, tw);
        var resultCache = sb.ToString();

        // detect itext (or html) format of response
        XmlParser parser;
        using (var reader = GetXmlReader(resultCache))
        {
            while (reader.Read() && reader.NodeType != XmlNodeType.Element)
            {
                // no-op
            }

            if (reader.NodeType == XmlNodeType.Element && reader.Name == "itext")
                parser = new XmlParser();
            else
                parser = new HtmlParser();
        }

        // Create a document processing context
        var document = new Document();
        document.Open();

        // Associate output with response stream
        var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream);
        pdfWriter.CloseStream = false;

        // Create the pdf file in the directory system
        var fileStream = new FileStream(myPdfFilePath, FileMode.Create);
        var pdfWriter2 = PdfWriter.GetInstance(document, fileStream);

        // this is as close as we can get to being "success" before writing output
        // so set the content type now
        viewContext.HttpContext.Response.ContentType = "application/pdf";

        // parse memory through document into output
        using (var reader = GetXmlReader(resultCache))
        {
            parser.Go(document, reader);
        }

        fileStream.Close();

        // Send an email to the claimant
        Thread.Sleep(100);
        if (File.Exists(myPdfFilePath))
        {
            var subject = "PDF Documents";

            var body = Config.GetContent(ContentParams.CLAIM_DOCUMENT_EMAIL_BODY_TEXT);

            bool success;
            string errorMessage;

            Email.Send(myEmailAddress, subject, body, out success, out errorMessage, myPdfFilePath);
        }

        pdfWriter.Close();
        pdfWriter2.Close();

    }

It would be nice if this capability were somehow incorporated into the current RazorPDF project.

A: why not just get the stream via a web request to the url?
string razorPdfUrl="http://...";
var req = HttpWebRequest.Create(RazorPDFURL);
using (Stream pdfStream = req.GetResponse().GetResponseStream())
{
    ...
}


text:
Q: How to make a "perfect" hover using jQuery? Well, I've almost achieved what I was aiming for. There's an image and when hovered, a div fades over with text and background. The problem is when the user hovers the "new" div (text and background).
Here's the HTML:

Name

Job description

Name

Job description

Name

Job description

Name

Job description

Name

Job description

Name

Job description

Name

Job description

Name

Job description

Here's the jQuery I used:
$(document).ready(function() {
    $("div.admin-img").hover(
        function () {
            $(this).siblings('.admin-txt').stop(true,true).fadeIn(100);
        },
        function () {
            $(this).siblings('.admin-txt').stop(true,true).fadeOut(100);
        });
    $("div.other-img").hover(
        function () {
            $(this).siblings('.other-txt').stop(true,true).fadeIn(100);
        },
        function () {
            $(this).siblings('.other-txt').stop(true,true).fadeOut(100);
        });
});

How can I make it better?
And, on small images, how can I make the background cover the whole image?
Thanks in advance,
Dani.

A: The problem is that you've used the hover toggle on the parent div. Once you hover over the child div your parent looses focus and therefore fires the unhover event.
You should do a check in your unhover event to determine whether you've moved the cursor into the child and cancel the event if this is the case.

A: Another alternative is to simply position your div and make it opacity = 0. Then, you assign the hover to the overlaid div and fade it to 100% opacity. No more hover ambiguity.

A: http://jsfiddle.net/p8gWf/
Changes made on the javascript portion.


text:
Q: Solving recurrences of the form $T(n)=aT(n/a)+Θ(nlgn)$ On pages 95 and 96 of the third edition of the CLRS book, we find
the following, which applies here since $a=b$ is all
it takes to block the application of the Master Theorem: "Although
$n\lg n$ is asymptotically larger than n, it is not polynomially
larger because the ratio $\tfrac{n\lg n}{n}=\lg n$ is asymptotically
less than $n^{\epsilon}$ for any positive constant $\epsilon$. Consequently,
the recurrence falls into the gap between case 2 and case 3." For a solution, the authors send us to exercise 4.6.2 on page 106:
"Show that if $f\left(n\right)=\Theta\left(n^{\log_{b}a}\lg^{k}n\right)$,
where $k\geq0$, then the master recurrence has solution $T\left(n\right)=\Theta\left(n^{\log_{b}a}\lg^{k+1}n\right)$.
For simplicity, confine your analysis to exact powers of b."
(Here $\lg^k n$ is CLRS's notation for $(\log_2 n)^k$.)
This is where I am starting to have problems...

A: Since  this question  is asked  frequently I  will try  to work  out a
solution for generic positive integers $a$ where $a\ge 2$.
Suppose  we have  $T(0)=0$  and
$$T(1)=T(2)=\ldots  =T(a-1)=1$$
and  for $n\ge  a$
$$T(n) = a T(\lfloor  n/a \rfloor) + n \lfloor \log_a  n \rfloor.$$
Furthermore let the base $a$ representation of $n$ be
$$n = \sum_{k=0}^{\lfloor \log_a n \rfloor} d_k a^k.$$
Then  we can  unroll the  recurrence to  obtain the  following exact
formula for $n\ge a$
$$T(n) = a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
a^j \times (\lfloor \log_a n \rfloor - j) \times
\sum_{k=j}^{\lfloor \log_a n \rfloor} d_k a^{k-j}.$$
Now to  get an upper bound  consider a string consisting  of the digit
$a-1$ to obtain
$$T(n) \le a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
a^j \times (\lfloor \log_a n \rfloor - j) \times
\sum_{k=j}^{\lfloor \log_a n \rfloor} (a-1) \times a^{k-j}.$$
This simplifies to
$$a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
a^j \times (\lfloor \log_a n \rfloor - j) \times (a-1)
\sum_{k=0}^{\lfloor \log_a n \rfloor-j} a^k$$
which is
$$a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
a^j \times (\lfloor \log_a n \rfloor - j)
(a^{\lfloor \log_a n \rfloor + 1 -j} -1)$$
which turns into
$$a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
(\lfloor \log_a n \rfloor - j)
(a^{\lfloor \log_a n \rfloor + 1} - a^j).$$
The sum produces four terms.
The first is
$$\lfloor \log_a n \rfloor^2
a^{\lfloor \log_a n \rfloor + 1}.$$
The second is
$$- \lfloor \log_a n \rfloor
\frac{a^{\lfloor \log_a n \rfloor}-1}{a-1}.$$
The third is
$$- \frac{1}{2} a^{\lfloor \log_a n \rfloor + 1}
(\lfloor \log_a n \rfloor -1) \lfloor \log_a n \rfloor$$
and the fourth is
$$\frac{1}{(a-1)^2}
\left(a + a^{\lfloor \log_a n \rfloor}
(\lfloor \log_a n \rfloor (a-1) -a)\right).$$
This bound  represented by these four  terms plus the  leading term is
actually attained and cannot be  improved upon. For the asymptotics we
only need the dominant term, which is
$$\left(a - \frac{1}{2} a \right)
\lfloor \log_a n \rfloor^2
a^{\lfloor \log_a n \rfloor}
= \frac{1}{2} a \lfloor \log_a n \rfloor^2
a^{\lfloor \log_a n \rfloor}.$$
Now for  the lower bound,  which occurs with  a one digit  followed by
zeroes to give
$$T(n) \ge a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
a^j \times (\lfloor \log_a n \rfloor - j) \times
a^{\lfloor \log_a n \rfloor-j}.$$
This simplifies to
$$a^{\lfloor \log_a n \rfloor}
+ \sum_{j=0}^{\lfloor \log_a n \rfloor -1}
(\lfloor \log_a n \rfloor - j) \times
a^{\lfloor \log_a n \rfloor}$$
which is
$$a^{\lfloor \log_a n \rfloor}
+ a^{\lfloor \log_a n \rfloor}
\sum_{j=0}^{\lfloor \log_a n \rfloor -1}
(\lfloor \log_a n \rfloor - j)$$
which finally produces
$$a^{\lfloor \log_a n \rfloor}
+ a^{\lfloor \log_a n \rfloor}
\sum_{j=1}^{\lfloor \log_a n \rfloor} j$$
or
$$a^{\lfloor \log_a n \rfloor}
+ \frac{1}{2}
\lfloor \log_a n \rfloor (\lfloor \log_a n \rfloor +1)
a^{\lfloor \log_a n \rfloor}.$$
The dominant term here is
$$\frac{1}{2}
\lfloor \log_a n \rfloor^2 a^{\lfloor \log_a n \rfloor}.$$
Joining the dominant terms of the  upper and the lower bound we obtain
the asymptotics
$$\color{#00A}{\lfloor \log_a n \rfloor^2 \times
a^{\lfloor \log_a n \rfloor}
\in \Theta\left((\log_a n)^2 \times a^{\log_a n}\right)
= \Theta\left((\log n)^2 \times n\right)}.$$
This MSE link has a series of similar calculations.

A: This is amenable to analysis by the Akra-Bazzi method. The calculations go like this, using the notation of the Wikipedia article:
\begin{eqnarray*}
k & = & 1 \\
a_1 & = & a \\
b_1 & = & 1/a \\
g(x) & = & x \log x \\
h(x) & = & 0 \\
p & = & 1 \Leftarrow a_1 b_1=1 \\
T(x) & = & \Theta \left ( x \left ( 1 + \int_1^x \frac{u \log u}{u^{p+1}} du \right ) \right ) \\
& = & \Theta \left ( x \left ( 1 + \Theta \left (\log(x)^2 \right ) \right ) \right ) \\
& = & \Theta \left ( x \log(x)^2 \right )
\end{eqnarray*}
This may not help you that much, as you may not be able to prove that the Akra-Bazzi method works.


text:
Q: REGEXP_REPLACE in snowflake I have the old_column in the snowflake table and would like to convert the values to the new column as mentioned below.
I tried with REGEXP_REPLACE and couldn't able to write exact logic.

old_column
new_column

1,2,4
ACT,SAT,TOEFL

6,3
LNAT,IELTS

5,1
ACT,BMAT

A: Your new_columns does not shows a random order. Assuming its ordered, one version of query can be as follows (CASE can be added as needed further based on data values) -
with data_cte as
(select * from values
('1,2,4'),
('6,3'),
('5,1')
)
select distinct
listagg (value,',')
within group (order by index)
over (partition by seq) old_value,
listagg (col,',')
within group (order by value::number)
over (partition by seq) new_value
from (
select t.*,
case
when value=1 then 'ACT'
when value=2 then 'SAT'
when value=3 then 'IELTS'
when value=4 then 'TOEFL'
when value=5 then 'BMAT'
ELSE 'LNAT'
end as col
from data_cte d , table(split_to_table(d.column1,',')) t
);
+-----------+---------------+
| OLD_VALUE | NEW_VALUE     |
|-----------+---------------|
| 1,2,4     | ACT,SAT,TOEFL |
| 6,3       | IELTS,LNAT    |
| 5,1       | ACT,BMAT      |
+-----------+---------------+


text:
Q: zendframe work with ubuntu 11 I have download the zendframe work v 1.11.5 on ubuntu 11 (every thing else is installed) after putting the command zf create project /var/www/name it gives me a lot of warnings,so how to set up the zend frame work properly..
the warning:

Note: This command created a web project, for more information setting up your
VHOST, please see docs/README
PHP
Warning:
require_once(PHP/CodeCoverage/Filter.php):
failed to open stream: No such file or
directory in
/usr/share/php/PHPUnit/Autoload.php on
line 46 PHP Stack trace:

A: I know the solution,the problem is with phpUnit and pear ,if any one try to install phpUnit from the repository then he will got the warning above,so you need to install it by pear.
try in the terminal:
pear channel-discover components.ez.no

pear channel-discover pear.symfony-project.com

sudo pear install phpunit/PHPUnit

however you will another probelm after doing line 3 because you need to upgrade pear so do this before line 3:
sudo pear upgrade

then DO Step 3 again
sudo pear install phpunit/PHPUnit

of course you need also to set the path in php.ini try(locate php.ini)
then in the file file add these :
include_path=".:/usr/share/php:/usr/share/pear:/usr/share/php/PHPunit:/usr/share/php/PEAR"

notice the path to pear and PHPUnit, so if your path different you have to locate your path ;)
hope thats help :)

A: Go to the any web directory say, /var/www/html/test
Now call the zf.sh file in the bin folder of zend framework to create new project
In my case I extracted the zend framework in /var/ww/html/zend-framework
So I called the zf.sh file as follows
/var/www/html/zend-framework/bin/zf.sh create project zendtest
Now a project called called " zendtest "  has been created in the current directory. This project will have four Sub folders.
Now we need to include the Libraries in the zend framework in our new project. To do that, just copy the folder called Zend from the library folder of our zend framework.  (in my case I copied /var/ww/html/zend-framework/library/Zend ).
That's all, we have created a sample  project in Zend framework. We can test it using browsing the Public folder in the new project
http://localhost/ test/zendtest/public/


text:
Q: How to copy list of files in parallel to list of destinations? Python I have src_list and dst_list, two lists of the same length.
src_list contains paths to existing files.
dst_list contains paths to maybe existing files to maybe overwrite (not folders!).
src_list[i] should correspond to dst_list[i].
I want to copy every src_list[i] to dst_list[i], in (multiprocessing, not threading) parallel.
I want the call to be blocking, meaning all processes should be joined  before moving on.

Examples of lists:
src_list = [

r"/data/one/f1.txt",
r"/data/one/f2.txt",
r"/data/two/f3.txt",
r"/data/three/f4.txt",
r"/data/four/five/f5.txt",
]

dst_list = [

r"/out1/f1.txt",
r"/out2/two/three/pook.txt",
r"/data/foo/bar/baz/f333.txt",
r"/kiko/f4",
r"/data/four/five/f5.txt",
]

really, just just paths to files. Please assume the lists are ~1000-5000 elements long.

What I seem to lack is the correct API call to parallelize over two iterables.

A: from concurrent.futures import ProcessPoolExecutor
from shutil import copyfile

with ProcessPoolExecutor() as executor:
    executor.map(copyfile, src_list, dst_list)

If you want to limit the number of processes that are working on this you can pass a max_workers argument inside the ProcessPoolExecutor() method.

A: you can try something like that:
from multiprocessing import Process
import shutil

def parallel_copy(src_lst, dst_list):
    if not src_lst or not dst_list or len(src_lst) != len(dst_list):
        raise ValueError('Cannot process inputs.')

    processes = [Process(target=shutil.copyfile, args=(src, dst)) for src, dst in zip(src_lst, dst_list)]
    [p.start() for p in processes]
    [p.join() for p in processes]

A: Full answer, based on @tibipin's. This one also creates the dst folder structure if needed.
from concurrent.futures import ProcessPoolExecutor
import shutil
from typing import Iterable

def copy_single_file_create_dirs(src, dst):
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    shutil.copyfile(src, dst)

def copy_src_to_dst_overwrite_parallel(
        existing_src_files: Iterable[str],
        dst_files: Iterable[str],
        max_workers=None,
):
    with ProcessPoolExecutor(max_workers=max_workers) as executor:
        executor.map(copy_single_file_create_dirs, existing_src_files, dst_files)

The copy_single_file_create_dirs function can't be defined as an inner function because then it needs to be pickled which doesn't work. This is the cleanest I could get.


text:
Q: How do I turn off predictive text in the Gboard on ios? I'm on the most recent version of iOS. I use GBoard and I'd like to eliminate the row of words that they offer based on what they think you're trying to type.
There is an option to get rid of emoji suggestions and also auto correction, but I don't see any options to get rid of prediction more generally.
Is that feature available for GBoard?


text:
Q: Why did the Engineers leave the clues to their military installation (as opposed to somewhere else)? Dr. Shaw (and her boy friend) told the crew of Prometheus in their presentation that Engineers left - as far back as 35,000 years - clues as to the location of their planet in the form of a star pattern in images found all over the globe.

"They want us to find them" - Dr. Elizabeth Shaw

When they researched the pattern, they found LV-223.
Except that:

*

*LV-223 was NOT their home planet, it was their secret military base dedicated to project "Kill 'em all!"

*The base on LV-223 looked to be a temporary installation from 2000 years ago, NOT a permanent colony from 35,000+ years ago (I don't have canon proof, just the impression I got from the movie).
It seems like the wrong place to leave directions to on both accounts.
Is there some canon explanation (movie detail I missed, interviews/deleted scenes) that explain this seeming contradiction?

A: The only thing we know from the movie is that about 2000 years before the crew arrive at the planet some Engineers were planning on using the black liquid to destroy life on Earth.
The military base was certainly not a "secret" as primitive cultures dating back 35000 years were told about its location by the Engineers.
It is safe to assume that the Engineers did not always intend to "kill 'em all" but that at some point prior to 2000 years before the crew arrive they changed their viewpoint on humanity. Shaw and David say as much at the end of the movie

Shaw: "They created us. Then they tried to kill us. They changed their minds. I deserve to know why."
David:...Does it matter why they changed their minds?

As far as why they told them the location of one of their outposts, rather than their home planet we can only speculate, though it seems likely that it was just a precaution.
Note: I reviewed the scene that had the "invitations" from the primitive cultures and all but one* of the drawings were dated BCE (from before when we know that the Engineer's at the outpost were attempting to kill all humans). This seems to corroborate the theory that these drawings really were invitations to meet, and that the Engineer's just hadn't changed their minds about us yet.
The last is Hawaiian, and is dated 680 CE which does not make much sense in any interpretation of the movie.


text:
Q: how to make sbcl automatically load a core? I have the core saved. How do I make sbcl load it automatically?

A: The -core command line argument should do it. From the man page:
   --core <corefilename>
      Use the specified Lisp core file instead of the default. (See the FILES section  for  the
      standard  core,  or the system documentation for SB-EXT:SAVE-LISP-AND-DIE for information
      about how to create a custom core.) Note that if the Lisp core  file  is  a  user-created
      core  file,  it  may  run  a  nonstandard  toplevel which does not recognize the standard
      toplevel options.

A: You can use sbcl --core your.core to load it automatically.


text:
Q: Image hover overlay with text - text position Good evening,
I am trying to make image hover overlay with text, but displayed text is always on the top of the image. I would like to display it in the middle of it.
I've tried padding etc, but it moved the overlay as well, that it covered also the free space below the image. Could you please help me, how to margin only text from top? Thank you!
EDIT: Or the best solution would be, if I could include another div with text only. Because I need to include text with html tags and it's not possible this way, via "content:"
http://jsfiddle.net/sL6bjebx/
Here is CSS code:
.image {
    position:relative;
    margin: 0 auto;

}
.image img {
    width:100%;
    vertical-align:;
}
.image:after {
    content:'Here is some text..';
    color:#fff;
    position:absolute;
    width:100%; height: 100%; max-height:100%;

    top:0; left:0;
    background:rgba(0,0,0,0.75);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:hover:after {
    opacity:1;
}

A: If your overlay text is going to be a one liner then you can use line-height css property to make it vertically center aligned
.image:after {
    content:'Here is some text..';
    color:#fff;
    position:absolute;
    width:100%; height: 100%; max-height:100%;
    top:0; left:0;
    background:rgba(0,0,0,0.75);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
    line-height:300px;
}

and if not, then I will suggest to use another way to display the content.
such as :before just like this fiddle, Or you can use a
 tag as well instead of the :before tag check this fiddle.
.image:after {
    content:'';
    color:#fff;
    position:absolute;
    width:100%; height: 100%; max-height:100%;
    top:0; left:0;
    background:rgba(0,0,0,0.75);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
    z-index:1
}
.image:before {
    content:'Here is some text..';
    color:#fff;
    position:absolute;
    width:100%; height: 20px;
    top:0; left:0; right:0;
    bottom:0;
    opacity:0;
    margin:auto;
    z-index:2
}
.image:hover:after {
    opacity:1;
}
.image:hover:before {
    opacity:1;
}

A: Here is the solution with another div or something, where would be possible to insert text with HTML tags:

.image {
    position:relative;
    margin: 0 auto;
    width: 317px;
    height: 317px;
    text-align: center;

}
.image img {
    width:100%;
    vertical-align:;
}
.image .overlayText {
    color:#fff;
    position:absolute;
    width:100%; height: 100%; max-height:100%;
    line-height:317px;

    top:0; left:0;
    background:rgba(0,0,0,0.75);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
  margin:0;
}
.image:hover > .overlayText {
    opacity:1;
}

Here is some text

A: You should simply add line-height

.image {
    position:relative;
    margin: 0 auto;

}
.image img {
    width:100%;
    vertical-align:;
}
.image:after {
    content:'Here is some text..';
    color:#fff;
    position:absolute;
    width:100%; height: 100%; max-height:100%;
    line-height:317px;

    top:0; left:0;
    background:rgba(0,0,0,0.75);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:hover:after {
    opacity:1;
}


text:
Q: Comment function with MySQL and PHP I am making a comment function for every post that comes on website. Brief view :

*

*Every post has an id, when posted.

*When the pages loads, MySQL query checks that is there is a table for comment box or not, if not then it creates one.

*in the end of every comment table name, it has the post id for ex. if id of a post is 9 then the table name for this post will be feed_comment_9. (the table for comments is in another database)

*I was able to connect the comment table and post box in the html view

*But, when the INSERT INTO query turn came, i couldn't find a good way

My main question : Is there is any way i can connect these 2 database or can do anything that the insert query will go in the same comment table as of the post.
My codes :
while ($row = $results->fetch_assoc()) {
    //database change and creating and checking tables
    $dbc->select_db("feed_update_comment");
$create_comment_table = "CREATE TABLE  IF NOT EXISTS feed_comment_" . $row['id'] . "( id MEDIUMINT NOT NULL AUTO_INCREMENT, full_name varchar(40), comment varchar(120), date_time varchar(100), PRIMARY KEY (id))";
$result_create_comment_table = $dbc->query($create_comment_table);
   //creating and checking finishes

// making the comments box
    $dbc->select_db("feed_update_comment");
     $select_comment_table = "SELECT * FROM feed_comment_" . $row['id'] . " ORDER BY id";
$result_query_select_comment_table = $dbc->query($select_comment_table );
if(!$result_query_select_comment_table) {
    $result_select_comment_table = array("full_name" => "", "comment"=> "No comments yet.");

}
$id_result_comment = '';
echo '

<form class="comment_form" method="post" action="' .$_SERVER['PHP_SELF']  . '">
<input name="comment_full_name" type="text" class="input_comment_full_name" required>  </input>
<textarea required name="input_comment_text" type="text" class="input_comment_text" ></textarea><input class="submit_input" name="comment_submit" type="submit"></input>

 </form>' . $id_result_comment .'

';
while ($result_select_comment_table = $result_query_select_comment_table->fetch_assoc()) {
echo '

 ' . $result_select_comment_table["comment"] . '

' .
'
 ' .  $result_select_comment_table["full_name"]. '

' .
'
' . $result_select_comment_table["date_time"] . '

'
. '
';
}
    echo '

';
    echo '
';

    //making of comment box finishes

 //insert query (MAIN POINT)
  if ( isset($_POST["comment_submit"]) ) {
        $commenter_name = ($_POST["comment_full_name"]);
    $commenter_comment = ($_POST["input_comment_text"]);
        if (!empty($commenter_name) || !empty($commenter_comment)) {
            $dbc->select_db("feed_update_comment");
            $result_comment_submit = "INSERT INTO feed_comment_" . " (full_name,comment,date_time)" .  " VALUES('$commenter_name','$commenter_comment',DATE_FORMAT(NOW(),'%h:%i %p,  %W %M %e'))";
            $add_comment_submit = $dbc->query($result_comment_submit)
            or die ("");

        }

    }

extra : There are many of these types look at starting the post, down to it comment box. The problem is there will be dozen of it.

A: To know which post a comment belongs to, you can use an input with type="hidden" like this
<input type="hidden" name="comment_post_id" value="' . $row['id'] . '">

and access it like you would any other field via $_POST['comment_post_id'].

Unless you have lots (and you have to consider the definition for lots depending the dbms you're using) of comments, this is an overkill. You create many tables feed_comment_X which contain only few entries.
The basic solution is to have one table comments, which could look like this
CREATE TABLE comments (
  comment_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  post_id INT NOT NULL FOREIGN KEY REFERENCES posts (id) [ON..],
  full_name VARCHAR(32) NOT NULL,
  comment TEXT NOT NULL,
  date_time DATETIME NOT NULL
);

You save all comments in this table and don't need to check for existance of and (if necessary) create a new table on each page load.
To get all comments you simply (using parameterized statements)
SELECT full_name, comment, date_time FROM comments
  WHERE post_id = :post_id

And add a new entry by
INSERT INTO comments (post_id, full_name, comment, date_time) VALUES
  (:post_id, :full_name, :comment, :date_time)

This allows fast operations if you want to get additional info, eg. the number of comments each post has:
SELECT p.id, .., COUNT(c.post_id) AS total_comments FROM posts AS p
  LEFT JOIN comments AS c on c.post_id = p.id
  GROUP BY (p.id)


text:
Q: "Error: Not supported" when caused by `import("react-markdown")` I'm trying to import react-markdown, but I'm getting Error: Not supported
module.exports = import("react-markdown");

A: You are exporting the react markdown library. In Next.js, you should not export libraries

A: You can try importing the library first and export it directly (although I don't know why you would want to do that, as you can import it in the file where you're going to use the "exported library").
import ReactMarkdown from 'react-markdown'

module.exports = ReactMarkdown


text:
Q: JS alert in PHP as part of AJAX app I've got a PHP file that is being called to fill in a DIV via ajax. Everything works fine and dandy except I can't for the life of me get a JS alert box to pop up from the PHP.
Here is what I'm using to test (this is being tacked on toward the end of the PHP, I've also tried it toward the beginning, in the middle, etc):
 echo "does this show up?";
 echo "<script language='javascript'>alert('thanks!');</script>";

"does this show up?" is echoed and I can see the JS in codeinspector but no alert box. If I take that code and throw it in its own PHP file (so it is no longer embedded as part of a larger ajax app) it works just fine.
Any suggestions?

A: Sending back a script block via AJAX is the wrong way to do it. Instead, you should return a value (probably JSON using json_encode and then decode using the javascript JSON library) and then call alert from your script.
For example, something like this (untested, but you get the idea):
PHP:
echo json_encode(Array('OperationSucceeded' => 'true', 'Message' => 'test'));

Javascript:
retValObj = JSON.parse(retVal);
if (retValObj.Message != null) {
    alert(retValObj.Message);
}

A: javascript is parsed once during  page load. So if u put these code in page it works fine.... Browser does not parse on ajax loaded content...but we can make javascript function calls from ajax loaded content.


text:
Q: Screen resolution depends over the LCD screen or by the graphics card inside the machine? I am buying a HP laptop i.e. Probook 4540s the screen resolution that is by default offered by this machine is 1366 x 768, however I have also chosen to upgrade it and get a 2gb ATI Radeon card in it.
My question with a separate graphics card like above will it allow me to use higher screen resolutions like 1600 or 1920 etc.? Because as per my understanding when you have graphics card all display is handled by it?

A: You won't be able to increase the resolution. The screen resolution is limited to 1366 x 768 and any upgrade will not make a difference to the laptops ability to render a higher resolution (on the laptop itself).
However, depending on the other attributes of the card you might see a significant improvement in terms of FPS (Frames Per Second)

A: If the glass doesn't physically have the pixels, a better video card won't help with resolution - this is similar to the idea that an old tube TV can't show HD content at full resolution, even if you hook up a Bluray player
A better video card may help with frame rate, 3D, and color depth, or with driving an external display (which could be driven at a higher resolution than the native, laptop display).

A: Resolution is handled by graphics card and is limited to the resolutions offered by the display. For instance, you can have a monitor whose limit is 1366 x 768 and a graphics card whose limit is 1920 x 1080, the highest you can get is 1366 x 768. If you plug it into an HDTV and disable the built in display, your resolution will be 1920 x 1080.
You can have a smaller resolution on a higher monitor, but never a higher resolution on a lower monitor.
Here's a good way to remember it: think of your resolution like water, and your monitor like a bucket. You can always put less water in the bucket, but you can never put more water in than the bucket is physically capable of holding.


text:
Q: Very confused about ScrollMagic's onLeave event I've done a very bare ScrollMagic site based on one of the tutorials: http://www.oneniceday.com/Parallax-1/P2.html
If you View Source, then at the very end, there's this line:
triggerElement: "#pinned-trigger1",
duration: 2000,
triggerHook:"onLeave"

I don't understand about the "triggerHook:onLeave" line.
When is this onLeave event triggered?
I've been spending the past 2 days camping at the ScrollMagic documentation and reference site trying to figure out how the triggerElement and Hook works and when are the events like onLeave, onEnter, onCenter called but well....
Tks!

var controller = new ScrollMagic.Controller();

//create a new Scene
var scene = new ScrollMagic.Scene({
  triggerElement: "#pinned-trigger1",
  duration: 2000, //pin the #pinned-trigger1 element for 2000px
  //of scrolling
  triggerHook: "onLeave", //trigger the setpin method only when
  //top of #pinned-trigger section has hit the top of browser
  //window
  reverse: true
}).setPin("#pinned-element1").addTo(controller);

<!doctype html>

  <meta charset="utf-8">
  <title>Untitled Document</title>

  <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.min.css" rel="stylesheet">

Basic Pin

Elements are pinned for their respective pixel value set as the duration and released again.

This element will be pinned once it's trigger hits the top of the viewport and will have a duration of window height minus 100

This element will be pinned for a duration of 150px

Section Four!

A: trigger Hook-
there are 3 types of trigger Hooks which defines the start point of your animation, the position of the trigger Hook is in relation to the viewport.
onEnter => 1 (top of the screen)
onCenter => 0.5 (center of the screen)
onLeave => 0 (bottom of the screen)
By default trigger Hook is "onCenter"
trigger Element -
This defines the div ID or class the animation should start from. Once this trigger Element hits the trigger Hook your animation begins.


text:
Q: Stored procedure to create or update I am working on creating a Web API which will get account as the input parameter, which will have to create / update records in the table in SQL Server. So the web service will need to call the stored procedure which will accept the account. I created a sample table in the database with just two columns called Account and CounterSeq. I am trying to creating a stored procedure to create or update the records in the table.

Each account should have a CounterSeq associated with it. If the Account doesn't exists in the table, create Account name and associate CounterSeq = 001 to it. If the Account name already exists, just update like CounterSeq to CounterSeq + 1
+---------+----------------+
| Account | CounterSeq     |
+---------+----------------+
| ABC     | 001            |
| DEF     | 002            |
+---------+----------------+

For this I create a TableType like this
USE [Demo]
GO

-- Create the data type
CREATE TYPE projectName_TT AS TABLE
(
  Account      nvarchar(50),
  CounterSeq   int
)
GO

And the stored procedure as below but I am missing how to insert the new record like for a new Account how to set the CounterSeq to 001 ?
USE [Demo]
GO

 ALTER PROCEDURE [dbo].[uspInserorUpdateProjectName]
     @projectName_TT AS projectName_TT READONLY
 AS
 BEGIN
     SET NOCOUNT ON;
 BEGIN TRANSACTION;
     UPDATE prj
     SET prj.Account = tt.Account,
         prj.CounterSeq = tt.CounterSeq + 1
     FROM dbo.[ProjectName] prj
     INNER JOIN @projectName_TT tt ON prj.Account = tt.Account

     INSERT INTO [dbo].[ProjectName](Account, CounterSeq)
         SELECT tt.Account, tt.CounterSeq
         FROM @projectName_TT tt
         WHERE NOT EXISTS (SELECT 1
                           FROM [dbo].[ProjectName]
                           WHERE Account = tt.Account)

     COMMIT TRANSACTION;
END;

A: First, I believe that the table you passed in should only have one field (based on your description If the Account doesn't exists in the Database create Account name and associate CounterSeq 001 to it. If the Account name already exists just update like CounterSeq to CounterSeq+1)
You can use this query (put it in your stored procedure between the BEGIN TRANSACTION, COMMIT TRANSACTION.
 MERGE dbo.[ProjectName] prj
 USING @projectName_TT tt
 ON prj.Account = tt.Account
 WHEN MATCHED THEN UPDATE SET prj.CounterSeq = prj.CounterSeq+1
 WHEN NOT MATCHED THEN INSERT (Account,CounterSeq)
 VALUES (tt.Account, 1);


text:
Q: how to pass arguments to PhoneGap database transaction function I have a working PhoneGap database transaction where I am able to run a sql query and process the results.  However, in an effort to make it reusable, I need to be abe to pass arguments to the querying function.  There should a better way than declaring global variables and accessing them/resetting in the query function. Appreciate any help in converting this:
    //update images function
    function updateGalleryCovers() {
        var db = window.openDatabase("test db", "1.0", "Cordova DB", 200000);
        db.transaction(queryDB_u_g, errorCB);
    }
    //Query the database
    function queryDB_u_g(tx) {
        var query = 'SELECT cover_img, objectId FROM USER_GALLERY WHERE userId="'+getUserId()+'"';
        tx.executeSql(query, [], querySuccess_u_g, errorCB);
    }
//Query success callback
function querySuccess_u_g(tx, results) {
    var len = results.rows.length;
    for (var i=0; i<len; i++){
        // process results
    }
}

to something like this:
    //update images function
    function updateGalleryCovers(userid) {
        var db = window.openDatabase("test db", "1.0", "Cordova DB", 200000);
        db.transaction(queryDB_u_g, userid, errorCB);
    }
    //Query the database
    function queryDB_u_g(tx, userid) {
        var query = 'SELECT cover_img, objectId FROM USER_GALLERY WHERE userId="'+userid+'"';
        tx.executeSql(query, [], querySuccess_u_g, errorCB);
    }
//Query success callback
function querySuccess_u_g(tx, results) {
    var len = results.rows.length;
    for (var i=0; i<len; i++){
        // process results
    }
}

Thanks!

A: The transaction functions are offered by sqlite and not phonegap. Its true that you can't pass extra variables to the functions because of the method signature sqlite accepts.
But here's a work around for the same:
db_conn.transaction( function(tx){ your_function(tx, parameter1, parameter2) }, ErrorCallBack );

Here you are passing a dummy function to the transaction success callback and taking the transaction object along with it.
Hope that helps


text:
Q: Ftell reporting unexpected value while applying stream filter on a file pointer I am trying to calculate data written to a file using ftell while applying zlib.deflate stream filter. But ftell based size differs from actual size of data written to file.
Following is my code

$handler_read = fopen('image.jpg', 'rb');
$handler_write = fopen('image.jpg.z', 'wb');

$stream_filter = stream_filter_append($handler_write, 'zlib.deflate', STREAM_FILTER_WRITE);

printf("Cursor at: %s%s", ftell($handler_write), PHP_EOL);

$start = ftell($handler_write);
while(!feof($handler_read)) {

    $chunk = fread($handler_read, 1024*512);

    fwrite($handler_write, $chunk);

    printf("Cursor at: %s%s", ftell($handler_write), PHP_EOL);

}
$end = ftell($handler_write);

fclose($handler_read);
fclose($handler_write);

printf("Actual size: %s%s", filesize('image.jpg.z'), PHP_EOL );
printf("Curser based size: %s%s", $end - $start, PHP_EOL);

And following are the results
Cursor at: 0
Cursor at: 463944
Cursor at: 989108
Cursor at: 1055270
Actual size: 1148880
Curser based size: 1055270


text:
Q: DLL is not getting loaded after the modification I have a dll in which some text like myname is present and now i wanted to change it to mynaam. When i open the DLL with notepad in windows i am able to see the myname and i am changing this to mynaam and saving it. But my application is not even loading this dll. As myname and mynaam are having the same size the dll won't corrupt. Please suggest on this it would be a great help for me.  Do i need to use any binary editor or hex editor to do this?
I Observed another thing that i have renamed my original dll to some other name and made this modified dll with the original name. Then the application is still identifying the old DLL even though the name is different. I wonder how windows checks for a library. Please suggest on this also
Thanks StackOverFlow.....
Sunny

A: Try this: http://www.hexworkshop.com/

A: It is not recommended to do that but it is possible though. I did something like that once before. You will need to use some good hex editor. The only thing that you can change is string content. The string must be statically allocated within .data section(Global variable or C extenally linkage compiled variable with the contents initially set to some non-empty string). Next try to locate this string content with the HEX editor within your PE binary. After you managed to find it you are free to change the actual string content - just overwrite the old content with a new one. Hint - The length of a new content must not exceed the length of an old one including null terminator. When replacing an old content - don't forget to put null terminator explicitly in the end of a new string. Hint - OVERWRITE content but strongly DON'T ADD some new bytes.
Sincerely yours, Alex.


text:
Q: To update using set SET SERVEROUTPUT command I have written script to update using
    SET SERVEROUTPUT ON
    DECLARE
    bugNumber NUMBER:=1234;
    bugErrorCode NUMBER;
    bugErrorMessage VARCHAR2(10000);
    bugProductID NUMBER;
    BEGIN

and continued with it, but when I run it is throwing error as below so before beginning do I need to set any environment or how, as I am new to sql
./Updatebug.sh: line 1: SET: command not found
./Updatebug.sh: line 2: DECLARE: command not found
./Updatebug.sh: line 3: bugNumber: command not found
./Updatebug.sh: line 4: bugErrorCode: command not found
./Updatebug.sh: line 5: syntax error near unexpected token `('
./Updatebug.sh: line 5: `bugErrorMessage VARCHAR2(10000); '

Please help to resolve


text:
Q: My Blazor web app is giving me this error when I try to view a page I do not know what the below error is trying to tell me...
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at GSG.WebApp.Client.Pages.Index.BuildRenderTree(RenderTreeBuilder __builder) in C:\Users\ZachKoman\internalhrtool\GSG.WebApp\Client\Pages\Index.razor:line 0
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
The error began when I tried testing these filter input boxes.

        <BSLabel style="width=20%">Lastname: </BSLabel >
        <BSInput InputType="InputType.Text" placeholder="name" @bind-Value="lastname" />

        <BSLabel style="width=20%">Company: </BSLabel>
        <BSInput InputType="InputType.Text" placeholder="Company" @bind-Value="company"/>

        <BSLabel style="width=20%">Skill: </BSLabel>
        <BSInput InputType="InputType.Text" placeholder="Skill" @bind-Value="skill[0]"/>

        @for (int i = 1; i < skillFilterStatus; i++)
        {

                <BSLabel style="width=20%">Skill: </BSLabel>
                <BSInput InputType="InputType.Text" placeholder="Skill" @bind-Value="skill[i]"/>

        }
        @if(skillFilterStatus != 0)
        {

                <BSButton style="background-color: #ed1c24;" @onclick="FilterMinus"></BSButton>

        }
        @if(skillFilterStatus < 2)
        {

                <BSButton style="background-color: #8522e4;" @onclick="FilterClick"></BSButton>

        }

        <BSButton @onclick="ApplyFilter" style="background-color: #8522e4; color: white">Apply</BSButton>

@code
    private int skillFilterStatus = 0;
        private string lastname;
        private string company;
        private string[] skill;
        private void ApplyFilter(){

        Console.WriteLine(lastname+"-"+company+"-"+skill[0]+"-"+skill[1]+"-"+skill[2]);

    }


text:
Q: asp.net-core 2.0 Docker deploy I have an app developed in asp.net-core 2.0 and deployed on Linux with Docker.
So I created Docker image and run it on Linux server like:
docker run -p 80:80 --name my-container my-image:1.0

So from Docker image my-image:1.0 created container my-container
Now the issue is when I make some changes to my app and want to deploy that changes I have to stop/remove my-container and create a new one from new Docker image like:
docker stop my-container
docker rm my-container
docker run -p 80:80 --name my-container my-image:1.1

Is there any way to just update the container with the new image? Point is to use existing container with the new version of the image.

A:
Is there any way to just update the container with the new image?

No. But this is not what you need, since you said that your goal is the following one:

Now the issue is when I make some changes to my app and want to deploy that changes I have to stop/remove my-container and create a new one from new Docker image

Your Dockerfile looks certainly like that:
FROM microsoft/aspnetcore
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "myapp.dll"]

So, you just need to create a volume to export your workdir /app into the host filesystem, outside the container (use -v parameter with docker run). Then simply restart the container after having applied changes to your app.


text:
Q: How to use nested functions in r with different arguments? I am trying to write some functions in R where, i have defined a few functions and these functions take different arguments.
Example, i have defined these two functions, foo1 & foo2 -
foo1 <- function(x,y){
  return((x+y)*foo2(p,q))
}

foo2 <- function(p,q){
 return(p*q)
}

Now, i want to use these functions inside a wrapper function foo3 -
foo3 <- function(x,y,p,q){
 return(foo1(x,y))
}

But when i call
foo3(1,2,3,4)

i get the following error -
Error in foo2(p, q) : object 'p' not found
How can i resolve this error?


text:
Q: About Gotfocus and MouseClick event I have added one combo box on form and written Got focus event for that as DroppedDown=True.
But when I click on the combobox first that gotfocus event get call and items list get pop up. But after that due to mouse up event that list again pop down so i cann't see the pop up list.
How to tackle this??
Can low level event or global hooks help in this case??

A: I shall suggest you not to handle GotFocus event.

A: try this
if (MouseButtons == MouseButtons.None)
combobox.DroppedDown = true;


text:
Q: Simulation of Induction motor using Simulink / Simscape I wish to generate a training dataset for a Machine Learning system) of Induction Motor operation using the Induction Motor model in Simulink / Simscape. I am observing the Stator Currents and noting that each simulation run is almost identical to the next. Any idea about how to add variability like a real motor?

A: In order to see fluctuations, you should change the load in your motor.
Inputs to motors: Electrical power
Outputs of motors: Mechanical power
Motor's input behaves in many cases because of the mechanical load that is connected to it so you should connect variable mechanical loads to the output of your motor.


text:
Q: How to get the most recent row in group in mysql? In my mysql query, I try to get all threads with their most recent row.
    $query = "SELECT th.id, tm.message, tm.date_sent, tm.date_sent>tu.last_read_date AS new
              FROM thread th
              JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
              JOIN thread_message tm ON th.id=tm.thread_id
              JOIN (
                   SELECT thread_id, MAX(date_sent) date_sent
                   FROM thread_message
                   GROUP BY thread_id
              ) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
              ORDER BY tm.date_sent DESC";

This works, but the problem is, if there is two or more rows who's date is the most recent and they are the same date, then it will join with both of them. I need that third join statement to join with at most 1 row.
I also don't want to assume that the biggest id implies its the most recent row, because I could always change the dates manually later.
Does anyone know how to fix this?
Thanks

A: One way to do this is to establish a row number per group, in this case your group is thread_id and date_sent.  With MySql, you need to use user-defined variables to do this:
SELECT th.id,
    tm.message,
    tm.date_sent,
    tm.date_sent>tu.last_read_date AS new
FROM thread th
    JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
    JOIN (
        SELECT id,
               thread_id,
               message,
               date_sent,
               @rn:=IF(@prevthread_id=thread_id, @rn+1, 1) rn,
               @prevthread_id:=thread_id
        FROM thread_message, (SELECT @rn:=1, @prevthread_id:=0) t
        ORDER BY thread_id, date_sent DESC, id
    ) tm ON th.id=tm.thread_id
           AND tm.rn = 1
ORDER BY tm.date_sent DESC

Perhaps this is easier for you (but only because you're using mysql):
SELECT th.id,
    tm.message,
    tm.date_sent,
    tm.date_sent>tu.last_read_date AS new
FROM thread th
    JOIN thread_user tu ON th.id=tu.thread_id AND tu.user_id={$user_id}
    JOIN thread_message tm ON th.id=tm.thread_id
    JOIN (
        SELECT thread_id,
               id,
               MAX(date_sent) date_sent
        FROM thread_message
        GROUP BY thread_id
    ) q ON tm.thread_id = q.thread_id
           AND q.id = tm.id
           AND tm.date_sent = q.date_sent
ORDER BY tm.date_sent DESC

This will return an arbitrary id to join on.

A: Seems to me that if the query produces what you expect, with exception of the last JOIN you can just modify the GROUP BY which will only return one row.
JOIN (
      SELECT thread_id, MAX(date_sent) date_sent
      FROM thread_message
      GROUP BY thread_id
      ) q ON tm.thread_id = q.thread_id AND tm.date_sent = q.date_sent
      GROUP BY tm.date_sent
      ORDER BY tm.date_sent DESC";


text:
Q: What is the Google App Script to move to the first empty row? I have reviewed previously asked questions on this but still can't work out the code. I have a sheet with a significant number of rows of data in it. Rather than scroll down to the first empty row, I have created a button and on click of that button, I want the cursor to take me to column A of the first empty row. This is my  script at this point but I keep getting errors:

Can someone please help me.

A: Try this:
function getLastRow() {
  var sss = SpreadsheetApp.getActiveSheet();
  sheet.getRange(sss.getLastRow()+1,1).activate();
}

A: If I understand your question correctly, you just want to go the first empty row in your sheet, not the first empty cell in column A. If that's the case, this small piece of code should do it:
function getLastRow() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  sheet.getRange(lastRow + 1, 1).activate();
}

I hope this is what you wanted to accomplish.

A: Please try this:
function TestFindBlank() {
  //Jojo is rank that can be used for next
  var Jojo=GetFirstBlank('Sheet1','F6');
};

function GetFirstBlank(mysheetName, myrangeStr)
{
  var spreadsheet = SpreadsheetApp.getActive();
  var Mysheet=spreadsheet.getSheetByName(mysheetName);
  var Jojo=spreadsheet.getRange(myrangeStr).getNextDataCell(SpreadsheetApp.Direction.DOWN);
  if (Jojo.offset(1,0).isBlank() ) {
    return  Jojo.offset(1,0);
  }

  var Jojo=spreadsheet.getRange(Jojo.getA1Notation()).getNextDataCell(SpreadsheetApp.Direction.DOWN);
  return Jojo.offset(1,0);

}

A: Just run setupStartUpTrigger() one time to set it up.  Then close and open again and give it a little time and you'll end up at the bottom.
function startUp() {//You can put your menu in here too
  SpreadsheetApp.getUi().createMenu('My Tools')
    .addItem('Item Name', 'functionName')
    .addToUi();
  var sh=SpreadsheetApp.getActive().getSheetByName('Sheet1');
  sh.getRange(sh.getLastRow()+1,1).activate();
}
//setup an installable onOpen() trigger
//this will fire on opening the spreadsheet
function setupStartUpTrigger(){
  var ss=SpreadsheetApp.getActive();
  if(!isTrigger('startUp')){
    ScriptApp.newTrigger('startUp').forSpreadsheet(ss.getId()).onOpen().create();
  }
}

//this is nice to use to keep you from creating unnecessary triggers
function isTrigger(funcName){
  var r=false;
  if(funcName){
    var allTriggers=ScriptApp.getProjectTriggers();
    for(var i=0;i<allTriggers.length;i++){
      if(funcName==allTriggers[i].getHandlerFunction()){
        r=true;
        break;
      }
    }
  }
  return r;
}

A: Here next alternative to next blank or to next non blank cell:
function TestNextBlank_or_NotBlankUse() {
  var spreadsheet = SpreadsheetApp.getActive();
  var mysheet=spreadsheet.getSheetByName('Sheet1');
  var myrange=mysheet.getRange('Q1');

  var myrange=nextNonBlank(myrange); //First Non Blank
  Logger.log(myrange.getA1Notation());

  var myrange=nextNonBlank(myrange); //Second Non Blank
  Logger.log(myrange.getA1Notation());

  var myrange=nextNonBlank(myrange); //Third Non Blank
  Logger.log(myrange.getA1Notation());

  var myrange=mysheet.getRange('Q1');

  var myrange=nextBlank(myrange); //First Blank
  Logger.log(myrange.getA1Notation());

  var myrange=nextBlank(myrange); //Second Blank
  Logger.log(myrange.getA1Notation());

  var myrange=nextBlank(myrange); //Third Blank
  Logger.log(myrange.getA1Notation());

};

function nextBlank(theRange)
{
  if (theRange.offset(1, 0).isBlank()) return theRange.offset(1, 0);
  theRange=theRange.offset(1, 0);
  if (theRange.offset(1, 0).isBlank()) return theRange.offset(1, 0);
  theRange=theRange.getNextDataCell(SpreadsheetApp.Direction.DOWN).offset(1, 0);
  return theRange;
}

function nextNonBlank(theRange)
{
  if (theRange.offset(1, 0).isBlank()==false) return theRange.offset(1, 0);
  theRange=theRange.offset(1, 0);
  if (theRange.offset(1, 0).isBlank()==false) return theRange.offset(1, 0);
  theRange=theRange.getNextDataCell(SpreadsheetApp.Direction.DOWN);
  return theRange;
}

A: function TestFindBlankRow() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh=ss.getSheetByName('Sheet1');
  //Column A to T because you have formula in column U
  var Rslt=FirstBlankRange(sh,'A','T');  //0 : If Not Found
  Logger.log(Rslt);
  var Rslt=NextBlankRange(sh, Rslt, 'A','T');  //0 : If Not Found
  Logger.log(Rslt);
  var Rslt=LastBlankRange(sh,'A','T');  //0 : If Not Found
  Logger.log(Rslt);

};

function FirstBlankRange(Sheet, FirtColumn, LastColumn)
{
  for (a=1;a<Sheet.getLastRow()+1;a++)
  {
    var rr=Sheet.getRange(FirtColumn + a + ':' + LastColumn + a);
    var Rslt=rr.getValues().toString();
    if ((Rslt.length+1)==rr.getNumColumns())
    {
      return a;
    }
  }
  return 0;
}

function NextBlankRange(Sheet, CurPos, FirtColumn, LastColumn)
{
  for (a=CurPos+1;a<Sheet.getLastRow()+1;a++)
  {
    var rr=Sheet.getRange(FirtColumn + a + ':' + LastColumn + a);
    var Rslt=rr.getValues().toString();
    if ((Rslt.length+1)==rr.getNumColumns())
    {
      return a;
    }
  }
  return 0;
}

function LastBlankRange(Sheet, FirtColumn, LastColumn)
{
  for (a=Sheet.getLastRow();a>1;a--)
  {
    var rr=Sheet.getRange(FirtColumn + a + ':' + LastColumn + a);
    var Rslt=rr.getValues().toString();
    if ((Rslt.length+1)==rr.getNumColumns())
    {
      return a;
    }
  }
  return 0;
}